-
Notifications
You must be signed in to change notification settings - Fork 93
/
Copy pathConstructBinaryTreeFromInorderAndPostorderTraversal106.java
51 lines (45 loc) · 1.4 KB
/
ConstructBinaryTreeFromInorderAndPostorderTraversal106.java
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
/**
* Given inorder and postorder traversal of a tree, construct the binary tree.
*
* Note:
* You may assume that duplicates do not exist in the tree.
*
* For example, given
*
* inorder = [9,3,15,20,7]
* postorder = [9,15,7,20,3]
* Return the following binary tree:
*
* 3
* / \
* 9 20
* / \
* 15 7
*/
/**
* Definition for a binary tree node.
* public class TreeNode {
* int val;
* TreeNode left;
* TreeNode right;
* TreeNode(int x) { val = x; }
* }
*/
public class ConstructBinaryTreeFromInorderAndPostorderTraversal106 {
public TreeNode buildTree(int[] inorder, int[] postorder) {
if (inorder == null || postorder == null || inorder.length == 0 || postorder.length == 0 || inorder.length != postorder.length) return null;
int len = inorder.length;
return buildTree(inorder, 0, len-1, postorder, 0, len-1);
}
private TreeNode buildTree(int[] inorder, int ii, int ij, int[] postorder, int pi, int pj) {
if (ii > ij) return null;
int midVal = postorder[pj];
TreeNode curr = new TreeNode(midVal);
if (pi == pj) return curr;
int mid = ii;
while (inorder[mid] != midVal) mid++;
curr.left = buildTree(inorder, ii, mid-1, postorder, pi, pi+(mid-1-ii));
curr.right = buildTree(inorder, mid+1, ij, postorder, pi+(mid-ii), pj-1);
return curr;
}
}