对根节点的左子树进行中序遍历。
访问根节点。
对根节点的右子树进行中序遍历。

const bt = {
val: 1,
left: {
val: 2,
left: {
val: 4,
left: null,
right: null,
},
right: {
val: 5,
left: null,
right: null,
},
},
right: {
val: 3,
left: {
val: 6,
left: null,
right: null,
},
right: {
val: 7,
left: null,
right: null,
},
},
};
递归版
const inorder = (root) => {
if(!root) {return;}
inorder(root.left);
console.log(root.val);
inorder(root.right);
}
inorder(bt)
非递归版
const inorder = (root) => {
if(!root) {return;}
const stack = [];
let p = root;
while(stack.length || p){
while(p) {
stack.push(p);
p = p.left;
}
const n = stack.pop();
console.log(n.val);
p = n.right
}
}
inorder(bt)
4 2 5 1 6 3 7
这篇博客介绍了如何使用递归和非递归方法进行二叉树的中序遍历。首先展示了递归版本的代码,从根节点开始,先遍历左子树,然后访问根节点,最后遍历右子树。接着,提供了非递归版本的实现,利用栈来辅助遍历,依次压入左子节点,打印节点值,并跳转到右子节点。代码示例清晰地展示了两种遍历方式的工作流程。





