forked from chihungyu1116/leetcode-javascript
-
Notifications
You must be signed in to change notification settings - Fork 14
Expand file tree
/
Copy path106 Construct Binary Tree from Inorder and Postorder Traversal.js
More file actions
53 lines (44 loc) · 1.24 KB
/
Copy path106 Construct Binary Tree from Inorder and Postorder Traversal.js
File metadata and controls
53 lines (44 loc) · 1.24 KB
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
53
/**
* Definition for a binary tree node.
* function TreeNode(val) {
* this.val = val;
* this.left = this.right = null;
* }
*/
/**
* @param {number[]} inorder
* @param {number[]} postorder
* @return {TreeNode}
*/
var buildTree = function(inorder, postorder) {
if(inorder === null || postorder === null){
return null;
}
if(inorder.length !== postorder.length){
return null;
}
return generate(inorder, 0, inorder.length - 1, postorder, 0, postorder.length - 1);
};
var generate = function(inorder, il, ir, postorder, pl, pr){
if(il > ir || pl > pr){
return null;
}
var rootVal = postorder[pr];
var root = new TreeNode(rootVal);
var rootIndex = -1;
for(var i = il; i <= ir; i++){
var nodeVal = inorder[i];
if(nodeVal === rootVal){
rootIndex = i;
break;
}
}
if(rootIndex === -1){
return null;
}
var leftTreeSize = rootIndex - il;
var rightTreeSize = ir - rootIndex;
root.left = generate(inorder, il, rootIndex - 1, postorder, pl, pl + leftTreeSize - 1);
root.right = generate(inorder, rootIndex + 1, ir, postorder, pr - rightTreeSize, pr - 1);
return root;
}