File tree Expand file tree Collapse file tree 2 files changed +42
-0
lines changed
construct-binary-tree-from-inorder-and-postorder-traversal Expand file tree Collapse file tree 2 files changed +42
-0
lines changed Original file line number Diff line number Diff line change @@ -10,6 +10,8 @@ leetcode 测试
10
10
11
11
##### 包含的内容如下
12
12
13
+ https://leetcode.cn/problems/construct-binary-tree-from-inorder-and-postorder-traversal/
14
+
13
15
https://leetcode.cn/problems/number-of-arithmetic-triplets/
14
16
15
17
https://leetcode.cn/problems/7p8L0Z/
Original file line number Diff line number Diff line change
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
+ }
You can’t perform that action at this time.
0 commit comments