-
Notifications
You must be signed in to change notification settings - Fork 71
/
Copy pathres.ts
65 lines (55 loc) · 1.32 KB
/
res.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
64
65
/**
* Definition for a binary tree node.
*/
class TreeNode {
val: number
left: TreeNode | null
right: TreeNode | null
constructor(val?: number, left?: TreeNode | null, right?: TreeNode | null) {
this.val = (val===undefined ? 0 : val)
this.left = (left===undefined ? null : left)
this.right = (right===undefined ? null : right)
}
}
/**
* 递归
* @param root
*/
function inorderTraversal(root: TreeNode | null): number[] {
const result: number[] = [];
if (!root) {
return result;
}
if (root.left) {
result.push(...inorderTraversal(root.left));
}
result.push(root.val);
if (root.right) {
result.push(...inorderTraversal(root.right));
}
return result;
};
/**
* 迭代
* @param root
*/
function inorderTraversal2(root: TreeNode | null): number[] {
const result: number[] = [];
if (!root) {
return result;
}
const nodes = [];
let currentPointer = root;
while(nodes.length || currentPointer) {
// left
while (currentPointer) {
nodes.push(currentPointer);
currentPointer = currentPointer.left;
}
const singleNode = nodes.pop();
result.push(singleNode.val);
// right
currentPointer = singleNode.right;
}
return result;
};