参考网上代码手写了JS实现树的非递归遍历
// 实现树的遍历方法,主要包括BFS和DFS。其中DFS会考虑非递归方法,且涵盖中序,先序和后序
// date:2021.0913
//
function Tree(val ) {
this.val = val;
this.left = this.right = null;
}
// 树的层次遍历
function bfs(root) {
if(!root) return;
let arr = [];
arr.push(root);
while (arr.length >0){
let node = arr.shift() ;
console.log(node.val);
if(node.left){
arr.push(node.left);
}
if(node.right){
arr.push(node.right);
}
}
}
// 树的深度优先搜索 DFS
function dfs(root){
if(!root) return;
if(root.left) {
dfs(root.left);
}
if(root.right) {
dfs(root.right);
}
console.log(root.val);
}
// 中序遍历-非递归
function zhongXu(root) {
if(!root) return;
var stack = [];
var p = root;
while (stack.length > 0 || p) {
//代码段(i)一直遍历到左子树最下边,边遍历边保存根节点到栈中
while (p) {
stack.push(p);
p = p.left;
}
//代码段(ii)当p为空时,说明已经到达左子树最下边,这时需要出栈了
//要执行的操作
if(stack.length > 0) {
p = stack.pop();
console.log(p.val);
//进入右子树,开始新的一轮左子树遍历(这是递归的自我实现)
p = p.right;
}
}
}
//先序遍历-非递归
function xianXu(root) {
if(!root) return;
var stack = [];
var p = root;
while (stack.length > 0 || p) {
while (p) {
//首先打印根节点
console.log(p.val);
//将根节点存起来,方便找右节点
stack.push(p);
p = p.left;
}
if(stack.length > 0) {
p = stack.pop();
p = p.right;
}
}
}
// 后序遍历--非递归
function houXu(root) {
if(!root) return;
var cur = root;
var lastVisit = null;
var stack = [];
while (cur) {
stack.push(cur);
cur = cur.left;
}
while (stack.length > 0) {
cur = stack.pop();
if (cur.right == null || cur.right == lastVisit) {
console.log(cur.val);
lastVisit = cur;
}
else {
stack.push(cur);
cur = cur.right;
while (cur) {
stack.push(cur);
cur = cur.left;
}
}
}
}
// 创造案例并调试
let root = new Tree(1)
let node_2l = new Tree(2)
let node_2r = new Tree(3)
let node_32l = new Tree(4)
let node_32r = new Tree(5)
let node_33l = new Tree(6)
let node_33r = new Tree(7)
root.left = node_2l;
root.right = node_2r;
node_2l.left = node_32l;
node_2l.right = node_32r;
node_2r.left = node_33l;
node_2r.right = node_33r;
// console.log('树的层次遍历:')
// bfs(root);
// console.log('树的深度遍历:')
// dfs(root);
// console.log('树的中序遍历')
// zhongXu(root);
// console.log('树的先序遍历')
// xianXu(root);
console.log('树的后序遍历')
houXu(root);
参考:https://blog.csdn.net/z_ryan/article/details/80854233