題目描述是這樣的:
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 preorderTraversal(TreeNode root) {
ArrayList list=new ArrayList();
Stack stack=new Stack();
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;
}
}