# 144. 二叉树的前序遍历
var preorderTraversal = function(root) {
if (root === null) return [];
const arr = [];
dfs(root);
return arr;
function dfs(root) {
if (!root) return;
arr.push(root.val);
dfs(root.left);
dfs(root.right);
}
};
console.log(
preorderTraversal({
val: 1,
left: null,
right: {
val: 2,
left: {
val: 3,
},
right: null,
},
})
);
console.log(preorderTraversal(null));
console.log(
preorderTraversal({
val: 1,
left: { val: 4, left: { val: 2, left: null, right: null }, right: null },
right: { val: 3, left: null, right: null },
})
);
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
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