tree traversal


理解并背诵全文
Binary Tree Inorder Traversal

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
public List<Integer> (TreeNode root) {
List<Integer> ans = new ArrayList<Integer>();
if (root == null)
return ans;
Stack<TreeNode> stack = new Stack<TreeNode>();
while (root != null) {
stack.push(root);
root = root.left;
}
while (!stack.isEmpty()) {
root = stack.pop();
ans.add(root.val);
root = root.right;
while (root != null) {
stack.push(root);
root = root.left;
}
}
return ans;
}

Binary Tree Preorder Traversal

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
public List<Integer> preorderTraversal(TreeNode root) {
List<Integer> ans = new ArrayList<Integer>();
if (root == null)
return ans;
Stack<TreeNode> stack = new Stack<TreeNode>();
stack.push(root);
while (!stack.isEmpty()) {
root = stack.pop();
ans.add(root.val);
if (root.right != null) {
stack.push(root.right);
}
if (root.left != null) {
stack.push(root.left);
}
}
return ans;
}

Binary Tree Postorder Traversal

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
public List<Integer> postorderTraversal(TreeNode root) {
List<Integer> ans = new ArrayList<Integer>();
if (root == null)
return ans;
Stack<TreeNode> stack = new Stack<TreeNode>();
stack.push(root);
while (!stack.isEmpty()) {
root = stack.pop();
ans.add(root.val);
if (root.left != null) {
stack.push(root.left);
}
if (root.right != null) {
stack.push(root.right);
}
}
Collections.reverse(ans);
return ans;
}