Skip to content

Commit f064fdc

Browse files
committed
Add solution #106
1 parent 3d27de0 commit f064fdc

File tree

2 files changed

+36
-0
lines changed

2 files changed

+36
-0
lines changed

README.md

+1
Original file line numberDiff line numberDiff line change
@@ -111,6 +111,7 @@
111111
103|[Binary Tree Zigzag Level Order Traversal](./0103-binary-tree-zigzag-level-order-traversal.js)|Medium|
112112
104|[Maximum Depth of Binary Tree](./0104-maximum-depth-of-binary-tree.js)|Easy|
113113
105|[Construct Binary Tree from Preorder and Inorder Traversal](./0105-construct-binary-tree-from-preorder-and-inorder-traversal.js)|Medium|
114+
106|[Construct Binary Tree from Inorder and Postorder Traversal](./0106-construct-binary-tree-from-inorder-and-postorder-traversal.js)|Medium|
114115
108|[Convert Sorted Array to Binary Search Tree](./0108-convert-sorted-array-to-binary-search-tree.js)|Easy|
115116
110|[Balanced Binary Tree](./0110-balanced-binary-tree.js)|Easy|
116117
111|[Minimum Depth of Binary Tree](./0111-minimum-depth-of-binary-tree.js)|Easy|
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,35 @@
1+
/**
2+
* 106. Construct Binary Tree from Inorder and Postorder Traversal
3+
* https://leetcode.com/problems/construct-binary-tree-from-inorder-and-postorder-traversal/
4+
* Difficulty: Medium
5+
*
6+
* Given two integer arrays inorder and postorder where inorder is the inorder traversal of a
7+
* binary tree and postorder is the postorder traversal of the same tree, construct and return
8+
* the binary tree.
9+
*/
10+
11+
/**
12+
* Definition for a binary tree node.
13+
* function TreeNode(val, left, right) {
14+
* this.val = (val===undefined ? 0 : val)
15+
* this.left = (left===undefined ? null : left)
16+
* this.right = (right===undefined ? null : right)
17+
* }
18+
*/
19+
/**
20+
* @param {number[]} inorder
21+
* @param {number[]} postorder
22+
* @return {TreeNode}
23+
*/
24+
var buildTree = function(inorder, postorder) {
25+
if (inorder.length === 0) return null;
26+
27+
const root = postorder[postorder.length - 1];
28+
const index = inorder.indexOf(root);
29+
30+
return {
31+
val: root,
32+
left: buildTree(inorder.slice(0, index), postorder.slice(0, index)),
33+
right: buildTree(inorder.slice(index + 1), postorder.slice(index, -1))
34+
};
35+
};

0 commit comments

Comments
 (0)