题目描述是这样的:
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?
要求使用非递归方法。
可以利用栈来实现。
/**
* Definition for binary tree
* public class TreeNode {
* int val;
* TreeNode left;
* TreeNode right;
* TreeNode(int x) { val = x; }
* }
*/
public class Solution {
public ArrayList<Integer> preorderTraversal(TreeNode root) {
ArrayList<Integer> list=new ArrayList<Integer>();
Stack<TreeNode> stack=new Stack<TreeNode>();
if(root!=null){
stack.push(root);
while(!stack.empty()){
list.add(stack.peek().val);//这里只能用peek(),因为如果pop()的话会在获得val值的同时将结点弹出栈。
root=stack.pop();
if(root.right!=null){
stack.push(root.right);//右孩子先入栈,后出栈
}
if(root.left!=null){
stack.push(root.left);//左孩子后入栈,先出栈
}
}
}
return list;
}
}