【Leetcode】Binary Tree Preorder Traversal

来源:互联网 发布:centos 安装不上ibus 编辑:程序博客网 时间:2024/06/06 09:13

题目链接:https://leetcode.com/problems/binary-tree-preorder-traversal/

题目:

Given a binary tree, return the preorder traversal of its nodes' values.

For example:
Given binary tree {1,#,2,3},

   1    \     2    /   3

return [1,2,3].

Note: Recursive solution is trivial, could you do it iteratively?

思路:

前序遍历用栈保存,注意要先压入右结点,在压入左结点

算法:

public List<Integer> preorderTraversal(TreeNode root) {List<Integer> list = new ArrayList<Integer>();Stack<TreeNode> stack = new Stack<TreeNode>();if (root == null)return list;stack.push(root);while (!stack.isEmpty()) {TreeNode tmp = stack.pop();list.add(tmp.val);if (tmp.right != null) //先压right,先出left,不断的先访问leftstack.push(tmp.right);if (tmp.left != null)stack.push(tmp.left);}return list;}



0 0