二叉树的深度优先遍历

需求

给定一个二叉树,实现先序,中序,后续遍历

思路

先创建一颗二叉树,再进行上述操作

代码

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
function TreeNode(val) {
this.val = val;
this.left = null;
this.right = null;
}
//给定一个层次遍历产生的数组,生成一颗二叉树
function createTree_levelorder(arr) {
let rootval = arr.shift();
let queue = [];
if (rootval) {
let root = new TreeNode(rootval); //新建根节点
queue.push(root); //存入到队列中
while (queue.length) { //当队列不为空时,出队并进入相关节点
let node = queue.shift();
let leftval = arr.shift();
let rightval = arr.shift();
if (leftval !== '#') { //左子树不为空
let left = new TreeNode(leftval); //新建节点
queue.push(left);
node.left = left;
}
if (rightval !== '#') {
let right = new TreeNode(rightval);
queue.push(right);
node.right = right;
}

}
return root;
}
}

let arr = ['a', 'b', 'c', 'd', '#', '#', 'e', '#', 'f', '#', '#', '#', '#'];
let root = createTree_levelorder(arr);

function PreOrder(root, arr = []) { //先序遍历
if (root) {
arr.push(root.val);
PreOrder(root.left, arr);
PreOrder(root.right, arr);
} else {
arr.push('#');
}
}
let res = [];
PreOrder(root, res);
console.log(res);
//'a', 'b', 'd', '#', 'f', '#', '#', '#', 'c', '#', 'e', '#', '#'
function InOrder(root, arr = []) { //中序遍历
if (root) {
InOrder(root.left, arr);
arr.push(root.val);
InOrder(root.right, arr);
} else {
arr.push('#');
}
}
let res2 = [];
InOrder(root, res2);
console.log(res2);
//'#', 'd', '#', 'f', '#', 'b', '#', 'a', '#', 'c', '#', 'e', '#'
function PostOrder(root, arr = []) {
if (root) {
PostOrder(root.left, arr);
PostOrder(root.right, arr);
arr.push(root.val);
} else {
arr.push('#');
}
}
let res3 = [];
PostOrder(root, res3);
console.log(res3);
//'#', '#', '#', 'f', 'd', '#', 'b', '#', '#', '#', 'e', 'c', 'a'

二叉树的深度优先遍历
https://blog-theta-ten.vercel.app/2021/08/22/二叉树的深度优先遍历/
作者
Chen
发布于
2021年8月22日
许可协议