Skip to content

Commit 0d0eef9

Browse files
committed
Add solution #889
1 parent c167e72 commit 0d0eef9

File tree

2 files changed

+44
-0
lines changed

2 files changed

+44
-0
lines changed

Diff for: README.md

+1
Original file line numberDiff line numberDiff line change
@@ -420,6 +420,7 @@
420420
875|[Koko Eating Bananas](./0875-koko-eating-bananas.js)|Medium|
421421
876|[Middle of the Linked List](./0876-middle-of-the-linked-list.js)|Easy|
422422
884|[Uncommon Words from Two Sentences](./0884-uncommon-words-from-two-sentences.js)|Easy|
423+
889|[Construct Binary Tree from Preorder and Postorder Traversal](./0889-construct-binary-tree-from-preorder-and-postorder-traversal.js)|Medium|
423424
890|[Find and Replace Pattern](./0890-find-and-replace-pattern.js)|Medium|
424425
901|[Online Stock Span](./0901-online-stock-span.js)|Medium|
425426
905|[Sort Array By Parity](./0905-sort-array-by-parity.js)|Easy|
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,43 @@
1+
/**
2+
* 889. Construct Binary Tree from Preorder and Postorder Traversal
3+
* https://leetcode.com/problems/construct-binary-tree-from-preorder-and-postorder-traversal/
4+
* Difficulty: Medium
5+
*
6+
* Given two integer arrays, preorder and postorder where preorder is the preorder traversal of a
7+
* binary tree of distinct values and postorder is the postorder traversal of the same tree,
8+
* reconstruct and return the binary tree.
9+
*
10+
* If there exist multiple answers, you can return any of them.
11+
*/
12+
13+
/**
14+
* Definition for a binary tree node.
15+
* function TreeNode(val, left, right) {
16+
* this.val = (val===undefined ? 0 : val)
17+
* this.left = (left===undefined ? null : left)
18+
* this.right = (right===undefined ? null : right)
19+
* }
20+
*/
21+
/**
22+
* @param {number[]} preorder
23+
* @param {number[]} postorder
24+
* @return {TreeNode}
25+
*/
26+
var constructFromPrePost = function(preorder, postorder) {
27+
if (!preorder.length) return null;
28+
29+
const root = new TreeNode(preorder[0]);
30+
if (preorder.length === 1) return root;
31+
32+
const leftSize = postorder.indexOf(preorder[1]) + 1;
33+
root.left = constructFromPrePost(
34+
preorder.slice(1, leftSize + 1),
35+
postorder.slice(0, leftSize)
36+
);
37+
root.right = constructFromPrePost(
38+
preorder.slice(leftSize + 1),
39+
postorder.slice(leftSize, -1)
40+
);
41+
42+
return root;
43+
};

0 commit comments

Comments
 (0)