1
2
3
4
5
6
7
8
9
/**
* Definition for a binary tree node.
* public class TreeNode {
* int val;
* TreeNode left;
* TreeNode right;
* TreeNode(int x) { val = x; }
* }
*/

细细体会,其实关键点也不难,就是根据inorder里面的确定的left/right subtree对应的node的个数分别是多少,然后再在preorder/postorder中找到和根节点不相邻的部分的range。

  1. Construct Binary Tree from Preorder and Inorder Traversal
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
class Solution {
public TreeNode buildTree(int[] preorder, int[] inorder) {
return build(0, 0, inorder.length - 1, preorder, inorder);
}
public TreeNode build(int preStart, int inStart, int inEnd, int[] preorder, int[] inorder) {
if (preStart > preorder.length - 1 || inStart > inEnd) return null;
TreeNode root = new TreeNode(preorder[preStart]);
int inIndex = 0;
for (int i = inStart; i <= inEnd; ++i) {
if (preorder[preStart] == inorder[i]) {
inIndex = i;
break;
}
}
root.left = build(preStart + 1, inStart, inIndex - 1, preorder, inorder);
root.right= build(preStart + inIndex - inStart + 1, inIndex+1, inEnd, preorder, inorder);
return root;
}
}
  1. Construct Binary Tree from Inorder and Postorder Traversal
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
class Solution {
public TreeNode buildTree(int[] inorder, int[] postorder) {
return build(0, inorder.length-1, postorder.length-1, inorder, postorder);
}
public TreeNode build(int inStart, int inEnd, int postEnd, int[] inorder, int[] postorder) {
if (inStart > inEnd || postEnd < 0) return null;
TreeNode root = new TreeNode(postorder[postEnd]);
int index = 0;
for (int i = inStart; i <= inEnd; ++i) {
if (root.val == inorder[i]) {
index = i; break;
}
}
root.left = build(inStart, index - 1, postEnd - inEnd + index - 1, inorder, postorder);
root.right = build(index+1, inEnd, postEnd-1, inorder, postorder);
return root;
}
}