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 List<Integer> preorderTraversal(TreeNode root) {
Stack<TreeNode> stack = new Stack<TreeNode>();
List<Integer> list = new ArrayList<Integer>();
while(root != null){
while(root.left != null){
stack.push(root);
list.add(root.val);
root = root.left;
}
if(root.right != null){
list.add(root.val);
root = root.right;
}else{//叶子节点
list.add(root.val);
if(stack.empty()){//最后一个叶子
break;
}
while(!stack.empty()){//有祖先节点
TreeNode node = stack.pop();//返回栈顶元素
if(node.right != null){
root = node.right;
break;
}
if(stack.empty()){
root = null;
break;
}
}
}
}
return list;
}
}
Runtime: 384 ms
结果还凑合