先序遍历算法口诀
访问根节点;
对根节点的左子树进行先序遍历;
对根节点的右子树进行先序遍历。

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 preorder = (root) => {
if(!root) {return;}
console.log(root.val)
preorder(root.left)
preorder(root.right)
}
preorder(bt)
非递归版
const preorder = (root) => {
if(!root) {return;}
const stack = [root]
while(stack.length) {
const n = stack.pop()
console.log(n.val)
if(n.right) stack.push(n.right)
if(n.left) stack.push(n.left)
}
}
preorder(bt)
1 2 4 5 3 6 7
本文详细介绍了二叉树的先序遍历算法,包括递归和非递归两种实现方式,并提供了具体的JavaScript代码示例。通过先访问根节点,再遍历左子树和右子树,可以有效地遍历整个二叉树结构。示例代码展示了如何遍历给定的二叉树结构并打印节点值。
3万+

被折叠的 条评论
为什么被折叠?



