递归写法:
const preorderTraversal = function (root) {
if (!root) {
return []
}
let res = []
res.push(root.val)
res = res.concat(preorderTraversal(root.left))
res = res.concat(preorderTraversal(root.right))
return res
}
递归优雅版:
var preorderTraversal = function(root) {
return root ? [root.val, ...preorderTraversal(root.left), ...preorderTraversal(root.right)] : []
};
迭代写法:
const preorderTraversal = function (root) {
let res = []
let stack = []
if (root) stack.push(root)
while (stack.length > 0) {
const n = stack.pop()
res.push(n.val)
if (n.right) stack.push(n.right)
if (n.left) stack.push(n.left)
}
return res
}

本文详细介绍了二叉树的前序遍历算法,包括递归和迭代两种实现方式。递归方法直观但可能引起栈溢出,而迭代方法使用显式栈,更稳定且易于理解。
2449

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



