144. 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
4
5
1
\
2
/
3

return [1,2,3].

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

解法1:Iterative version 用stack

递归的就不写了,实在太简单。
用stack的方法的关键点在于,每一条路劲在探寻最左元素的时候,要把所有的parent node都push到stack中。
如果当前的路径到头了之后,从stack里pop出上一个parent,然后移步到右边。
注意终止条件是需要node!= null同时stack不为空。
C++

1

Java

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
/**
* Definition for a binary tree node.
* public class TreeNode {
* int val;
* TreeNode left;
* TreeNode right;
* TreeNode(int x) { val = x; }
* }
*/
public class Solution {
public List<Integer> preorderTraversal(TreeNode root) {
List<Integer> res = new ArrayList<Integer>();
if (root == null) {
return res;
}
Stack<TreeNode> stack = new Stack<TreeNode>();
TreeNode current = root;
while (current != null || !stack.isEmpty()) {
// push all left nodes into stack
while (current != null) {
res.add(current.val);
stack.push(current);
current = current.left;
}
if (!stack.isEmpty()) {
TreeNode temp = stack.pop();
current = temp.right; // move to the right cell
}
}
return res;
}
}