-
Notifications
You must be signed in to change notification settings - Fork 0
/
70-二叉树的遍历.ts
90 lines (83 loc) · 1.81 KB
/
70-二叉树的遍历.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
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
export 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)
}
}
function pre(head: TreeNode | null) {
// 栈
if (head) {
let stack: TreeNode[] = [];
stack.push(head);
while (stack.length) {
let cur = stack.pop();
if (cur) {
console.log('----',cur.val)
}
if (cur?.right) {
stack.push(cur.right)
}
if (cur?.left) {
stack.push(cur.left)
}
}
}
}
function inorderTraversal(root: TreeNode | null): number[] {
let ans:number[] = []
if (root) {
let stack: TreeNode[] = [];
while (stack.length || root) {
if (root) {
stack.push(root);
root = root.left;
} else {
root = stack.pop();
console.log(root.val);
root && ans.push(root.val)
root = root.right
}
}
}
return ans
};
// 后序遍历
function postorderTraversal(root: TreeNode | null): number[] {
let ans: number[] = [];
if (root) {
let s1: TreeNode[] = [];
let s2: TreeNode[] = [];
s1.push(root)
while (s1.length) {
root = s1.pop();
root && s2.push(root);
if (root?.left) {
s1.push(root.left)
}
if (root?.right) {
s1.push(root.right)
}
}
while (s2.length) {
ans.push(s2.pop().val)
}
}
return ans
};
// 层序遍历
function layer(root: TreeNode | null) {
if (!root) return
let queue = [root];
while (queue.length) {
let cur = queue.pop();
console.log(cur.val);
if (cur.left) {
queue.push(cur.left)
}
cur.right && queue.push(cur.right);
}
}