05 August 2008
Given a binary tree, return the preorder traversal of its nodes’ values.
Example:
1
2
3
4
5
6
7
8
Input: [1,null,2,3]
1
\
2
/
3
Output: [1,2,3]
Follow up: Recursive solution is trivial, could you do it iteratively?
前序遍历,根左右。
递归
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
/**
* Definition for a binary tree node.
* public class TreeNode {
* int val;
* TreeNode left;
* TreeNode right;
* TreeNode(int x) { val = x; }
* }
*/
class Solution {
public List<Integer> preorderTraversal(TreeNode root) {
List<Integer> result = new ArrayList<>();
preorderTraversalHelper(root, result);
return result;
}
private void preorderTraversalHelper(TreeNode root, List<Integer> result) {
if (root == null) {
return;
}
result.add(root.val);
preorderTraversalHelper(root.left, result);
preorderTraversalHelper(root.right, result);
}
}
迭代
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
37
/**
* Definition for a binary tree node.
* public class TreeNode {
* int val;
* TreeNode left;
* TreeNode right;
* TreeNode() {}
* TreeNode(int val) { this.val = val; }
* TreeNode(int val, TreeNode left, TreeNode right) {
* this.val = val;
* this.left = left;
* this.right = right;
* }
* }
*/
class Solution {
public List<Integer> preorderTraversal(TreeNode root) {
List<Integer> result = new ArrayList<>();
Stack<TreeNode> stack = new Stack<>();
stack.push(root);
while (!stack.isEmpty()) {
root = stack.pop();
if (root == null) {
continue;
}
stack.push(root.right);
stack.push(root.left);
if (root.left == null && root.right == null) {
result.add(root.val);
} else {
stack.push(new TreeNode(root.val)); // 这里不是直接加入root,而是新建一个node
}
}
return result;
}
}