findingsea's Studio.

Binary Tree Preorder/Postorder Traversal

Word count: 156 / Reading time: 1 min
2015/04/27 Share

树的前序和后序遍历是树相关算法的基本。就不多加解释了,直接上代码。

Binary Tree Preorder Traversal

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
public class Solution {
public List<Integer> preorderTraversal(TreeNode root) {
List<Integer> result = new LinkedList<Integer>();
generate(result, root);
return result;
}

private void generate(List<Integer> sequence, TreeNode node) {
if (node == null)
return;
sequence.add(node.val);
generate(sequence, node.left);
generate(sequence, node.right);
}
}

Binary Tree Postorder Traversal

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
public class Solution {
public List<Integer> postorderTraversal(TreeNode root) {
List<Integer> result = new LinkedList<Integer>();
generate(result, root);
return result;
}

private void generate(List<Integer> result, TreeNode node) {
if (node == null)
return;
generate(result, node.left);
generate(result, node.right);
result.add(node.val);
}
}
CATALOG
  1. 1. Binary Tree Preorder Traversal
  2. 2. Binary Tree Postorder Traversal