Skip to content
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.

Commit 4d93cc0

Browse files
authoredDec 17, 2019
Create 889-construct-binary-tree-from-preorder-and-postorder-traversal.js
1 parent c9b98c6 commit 4d93cc0

File tree

1 file changed

+43
-0
lines changed

1 file changed

+43
-0
lines changed
 
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,43 @@
1+
/**
2+
3+
Return any binary tree that matches the given preorder and postorder traversals.
4+
Values in the traversals pre and post are distinct positive integers.
5+
6+
Example 1:
7+
8+
Input: pre = [1,2,4,5,3,6,7], post = [4,5,2,6,7,3,1]
9+
Output: [1,2,3,4,5,6,7]
10+
11+
Note:
12+
13+
1 <= pre.length == post.length <= 30
14+
pre[] and post[] are both permutations of 1, 2, ..., pre.length.
15+
It is guaranteed an answer exists.
16+
If there exists multiple answers, you can return any of them.
17+
18+
*/
19+
20+
/**
21+
* Definition for a binary tree node.
22+
* function TreeNode(val) {
23+
* this.val = val;
24+
* this.left = this.right = null;
25+
* }
26+
*/
27+
/**
28+
* @param {number[]} pre
29+
* @param {number[]} post
30+
* @return {TreeNode}
31+
*/
32+
const constructFromPrePost = function(pre, post) {
33+
let i = 0,
34+
j = 0
35+
return (function dfs() {
36+
let val = pre[i++]
37+
let node = new TreeNode(val)
38+
if (val !== post[j]) node.left = dfs()
39+
if (val !== post[j]) node.right = dfs()
40+
j++
41+
return node
42+
})()
43+
}

0 commit comments

Comments
 (0)
Please sign in to comment.