JS二叉树的深度优先、广度优先实现代码
class Node {
constructor(data) {
this.data = data;
this.left = null;
this.right = null;
}
}
(function() {
const root = new Node(2);
root.left = new Node(3);
root.right = new Node(4);
root.left.left = new Node(5);
root.left.right = new Node(6);
// DFS深度优先 递归遍历
// 1、先序遍历 优先访问节点 -> 左子树 -> 右子树
function clrMap(rootNode) {
if (!rootNode) return;
console.log('先序遍历打印====', rootNode.data);
clrMap(rootNode.left);
clrMap(rootNode.right);
}
// 2、中序遍历 优先访问左子树 -> 节点 -> 右子树
function lcrMap(rootNode) {
if (!rootNode) return;
lcrMap(rootNode.left);
console.log('中序遍历打印====', rootNode.data);
lcrMap(rootNode.right);
}
// 3、后序遍历 优先访问左子树 -> 右子树 -> 节点
function lrcMap(rootNode) {
if (!rootNode) return;
lrcMap(rootNode.left);
lrcMap(rootNode.right);
console.log('后序遍历打印====', rootNode.data);
}
console.log('=============***************=============');
clrMap(root);
console.log('=============***************=============');
lcrMap(root);
console.log('=============***************=============');
lrcMap(root);
console.log('=============***************=============');
// 广度优先 BFS
function bfs(rootNode) {
if (!rootNode) return;
const queue = [rootNode];
while (queue.length) {
const current = queue.shift();
if (!current) return;
console.log('广度优先遍历打印====', current.data);
if (current.left) queue.push(current.left);
if (current.right) queue.push(current.right);
}
}
bfs(root);
})()
代码打印结果
=============***************=============
VM183:20 先序遍历打印==== 2
VM183:20 先序遍历打印==== 3
VM183:20 先序遍历打印==== 5
VM183:20 先序遍历打印==== 6
VM183:20 先序遍历打印==== 4
VM183:40 =============***************=============
VM183:28 中序遍历打印==== 5
VM183:28 中序遍历打印==== 3
VM183:28 中序遍历打印==== 6
VM183:28 中序遍历打印==== 2
VM183:28 中序遍历打印==== 4
VM183:42 =============***************=============
VM183:36 后序遍历打印==== 5
VM183:36 后序遍历打印==== 6
VM183:36 后序遍历打印==== 3
VM183:36 后序遍历打印==== 4
VM183:36 后序遍历打印==== 2
VM183:44 =============***************=============
VM183:53 广度优先遍历打印==== 2
VM183:53 广度优先遍历打印==== 3
VM183:53 广度优先遍历打印==== 4
VM183:53 广度优先遍历打印==== 5
VM183:53 广度优先遍历打印==== 6