/**
* 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> s = new Stack<>();
ArrayList<Integer> ai = new ArrayList<>();
TreeNode pointer = root;
while(!s.empty() || pointer!=null){
if(pointer!=null){
s.push(pointer);
ai.add(pointer.val);
pointer = pointer.left;
}else{
pointer = s.pop().right;
}
}
return ai;
}
}
链表加数字的顺序也就是你遍历的顺序:先走到root, 加入root, 再走root 左边,最后走root 右边。
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?