Skip to content

Commit 14cf0ba

Browse files
committed
https://leetcode.cn/problems/construct-binary-tree-from-inorder-and-postorder-traversal/
1 parent 81b695b commit 14cf0ba

File tree

2 files changed

+42
-0
lines changed

2 files changed

+42
-0
lines changed

README.md

Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -10,6 +10,8 @@ leetcode 测试
1010

1111
##### 包含的内容如下
1212

13+
https://leetcode.cn/problems/construct-binary-tree-from-inorder-and-postorder-traversal/
14+
1315
https://leetcode.cn/problems/number-of-arithmetic-triplets/
1416

1517
https://leetcode.cn/problems/7p8L0Z/
Lines changed: 40 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,40 @@
1+
import { TreeNode } from "../binary-tree-inorder-traversal/TreeNode.ts";
2+
3+
export default function buildTree(
4+
inorder: number[],
5+
postorder: number[],
6+
): TreeNode | null {
7+
if (inorder.length === 0) return null;
8+
let post_idx = postorder.length - 1;
9+
const idx_map = new Map<number, number>();
10+
function helper(in_left: number, in_right: number) {
11+
// 如果这里没有节点构造二叉树了,就结束
12+
if (in_left > in_right) {
13+
return null;
14+
}
15+
16+
// 选择 post_idx 位置的元素作为当前子树根节点
17+
const root_val = postorder[post_idx];
18+
const root = new TreeNode(root_val);
19+
20+
// 根据 root 所在位置分成左右两棵子树
21+
const index = idx_map.get(root_val) ?? 0;
22+
23+
// 下标减一
24+
post_idx--;
25+
// 构造右子树
26+
root.right = helper(index + 1, in_right);
27+
// 构造左子树
28+
root.left = helper(in_left, index - 1);
29+
return root;
30+
}
31+
32+
// 从后序遍历的最后一个元素开始
33+
34+
// 建立(元素,下标)键值对的哈希表
35+
// let idx = 0;
36+
inorder.forEach((val, idx) => {
37+
idx_map.set(val, idx);
38+
});
39+
return helper(0, inorder.length - 1);
40+
}

0 commit comments

Comments
 (0)