-
Notifications
You must be signed in to change notification settings - Fork 0
/
03376-medium-inordertraversal.ts
63 lines (56 loc) · 1.24 KB
/
03376-medium-inordertraversal.ts
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
// ============= Test Cases =============
import type { Equal, Expect } from "./test-utils";
const tree1 = {
val: 1,
left: null,
right: {
val: 2,
left: {
val: 3,
left: null,
right: null,
},
right: null,
},
} as const;
const tree2 = {
val: 1,
left: null,
right: null,
} as const;
const tree3 = {
val: 1,
left: {
val: 2,
left: null,
right: null,
},
right: null,
} as const;
const tree4 = {
val: 1,
left: null,
right: {
val: 2,
left: null,
right: null,
},
} as const;
type cases = [
Expect<Equal<InorderTraversal<null>, []>>,
Expect<Equal<InorderTraversal<typeof tree1>, [1, 3, 2]>>,
Expect<Equal<InorderTraversal<typeof tree2>, [1]>>,
Expect<Equal<InorderTraversal<typeof tree3>, [2, 1]>>,
Expect<Equal<InorderTraversal<typeof tree4>, [1, 2]>>
];
// ============= Your Code Here =============
interface TreeNode {
val: number;
left: TreeNode | null;
right: TreeNode | null;
}
// 为什么 使用[T]?避免递归调用联合类型的分布律
type InorderTraversal<T extends TreeNode | null> = [T] extends [TreeNode]
? [...InorderTraversal<T["left"]>, T["val"], ...InorderTraversal<T["right"]>]
: [];
// ref:https://juejin.cn/post/7105757371346976775