# 114. 二叉树展开为链表
var flatten = function(root) {
const arr = []
dfs(root)
for (let i = 1; i < arr.length; i++) {
const prev = arr[i - 1],
cur = arr[i]
prev.left = null
prev.right = cur
}
function dfs(node) {
if (!node) return null
arr.push(node)
dfs(node.left)
dfs(node.right)
return node
}
}
console.log(
flatten({
val: 1,
left: {
val: 2,
left: {
val: 3,
},
right: {
val: 4,
},
},
right: {
val: 5,
right: {
val: 6,
},
},
})
)
function TreeNode(val, left, right) {
this.val = val === undefined ? 0 : val
this.left = left === undefined ? null : left
this.right = right === undefined ? null : right
}
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
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