树遍历模板:递归与迭代
一、面试常考点
1. 递归遍历
代码短但深树可能爆栈。
2. 迭代遍历
显式栈更可控。
二、示例代码
function preorder(root, res = []) {
if (!root) return res
res.push(root.val)
preorder(root.left, res)
preorder(root.right, res)
return res
}
三、应用场景
1. 结构序列化
树转字符串/数组。
2. 表达式求值
语法树后序遍历。