-
Notifications
You must be signed in to change notification settings - Fork 35
Expand file tree
/
Copy pathmorris.ts
More file actions
68 lines (61 loc) · 1.6 KB
/
morris.ts
File metadata and controls
68 lines (61 loc) · 1.6 KB
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
type Nullish<T> = T | null | undefined
interface ITreeNode {
left: Nullish<this>
right: Nullish<this>
}
/**
* Morris 中序遍历.
*/
function morris<T extends ITreeNode>(root: T, visit: (node: T) => void): void {
let cur: Nullish<T> = root
while (cur) {
if (cur.left) {
let pred: T | null = cur.left
while (pred.right && pred.right !== cur) {
pred = pred.right
}
if (!pred.right) {
pred.right = cur
cur = cur.left
} else {
pred.right = null
visit(cur)
cur = cur.right
}
} else {
visit(cur)
cur = cur.right
}
}
}
export { morris }
if (require.main === module) {
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
}
}
// https://leetcode.cn/problems/recover-binary-search-tree/description/
// eslint-disable-next-line no-inner-declarations
function recoverTree(root: TreeNode | null): void {
if (!root) return
let first: TreeNode | null = null
let second: TreeNode | null = null
let prev = new TreeNode(-Infinity)
morris(root, node => {
if (prev.val > node.val) {
if (!first) first = prev
second = node
}
prev = node
})
const tmp = first!.val
first!.val = second!.val
second!.val = tmp
}
}