-
Notifications
You must be signed in to change notification settings - Fork 2
/
ConstructBinaryTreefromInorderandPostorderTraversal.java
52 lines (46 loc) · 1.3 KB
/
ConstructBinaryTreefromInorderandPostorderTraversal.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
52
package leetcode;
/**
* Project Name : Leetcode
* Package Name : leetcode
* File Name : ConstructBinaryTreefromInorderandPostorderTraversal
* Creator : Edward
* Date : Nov, 2017
* Description : 106. Construct Binary Tree from Inorder and Postorder Traversal
*/
public class ConstructBinaryTreefromInorderandPostorderTraversal {
/**
* 3
/ \
9 20
/ \ / \
15 7 1 5
inorder : 15 9 7 3 1 20 5
postorder : 15 7 9 1 5 20 3
time : O(n)
space : O(n)
* @param inorder
* @param postorder
* @return
*/
int pInorder;
int pPostorder;
public TreeNode buildTree(int[] inorder, int[] postorder) {
pInorder = inorder.length - 1;
pPostorder = postorder.length - 1;
return helper(inorder, postorder, null);
}
public TreeNode helper(int[] inorder, int[] postorder, TreeNode end) {
if (pPostorder < 0) {
return null;
}
TreeNode root = new TreeNode(postorder[pPostorder--]);
if (inorder[pInorder] != root.val) {
root.right = helper(inorder, postorder, root);
}
pInorder--;
if ((end == null) || (inorder[pInorder] != end.val)) {
root.left = helper(inorder, postorder, end);
}
return root;
}
}