Leetcode-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?


先序遍历跟后序遍历类似,只是顺序不同,这里也是要求用的迭代法。可以通过栈来实现,每次从栈中拿出一个根放入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
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
/**
* Definition for binary tree
* public class TreeNode {
* int val;
* TreeNode left;
* TreeNode right;
* TreeNode(int x) { val = x; }
* }
*/

import java.util.*;

public class Solution {
public ArrayList<Integer> preorderTraversal(TreeNode root) {
//TODO 用迭代法前序遍历
ArrayList<Integer> result = new ArrayList<Integer>();

if (root == null){
return result;
}

Stack<TreeNode> stack = new Stack<TreeNode>();
TreeNode pre = null;
stack.push(root);

while(!stack.isEmpty()){
//将当前结点(根)放入result中,并将左右孩子放入栈中,右孩子先进,让左孩子在栈顶
TreeNode cur = stack.pop();
result.add(cur.val);
if(cur.right != null){
stack.push(cur.right);
}
if(cur.left != null){
stack.push(cur.left);
}
}

return result;
}
}

public class Solution {
public ArrayList<Integer> preorderTraversal(TreeNode root) {
//TODO 用递归法前序遍历
ArrayList<Integer> result = new ArrayList<Integer>();

if (root == null){
return result;
}

result.add(root.val);
result.addAll(preorderTraversal(root.left));
result.addAll(preorderTraversal(root.right));
return result;
}
}