leetcode
leetcode copied to clipboard
144. 二叉树的前序遍历
给你二叉树的根节点 root ,返回它节点值的 前序 遍历。
示例 1:

输入:root = [1,null,2,3]
输出:[1,2,3]
示例 2:
输入:root = []
输出:[]
示例 3:
输入:root = [1]
输出:[1]
示例 4:

输入:root = [1,2]
输出:[1,2]
示例 5:

输入:root = [1,null,2]
输出:[1,2]
提示:
树中节点数目在范围 [0, 100] 内 -100 <= Node.val <= 100
进阶:递归算法很简单,你可以通过迭代算法完成吗?
来源:力扣(LeetCode) 链接:https://leetcode-cn.com/problems/binary-tree-preorder-traversal 著作权归领扣网络所有。商业转载请联系官方授权,非商业转载请注明出处。
示例给的太简单了, 可能看不出什么规律来, 所以我搬了一个详细的树

- 递归遍历
const preorderTraversal = root => {
if (!root) return []
const res = [root.val]
if (root.left) {
res.push(...preorderTraversal(root.left))
}
if (root.right) {
res.push(...preorderTraversal(root.right))
}
return res
}
- 迭代 = 栈 + 深度优先搜索
const preorderTraversal = root => {
if (!root) return []
const stack = [root], res = []
while (stack.length) {
let curr = stack.pop()
res.push(curr.val)
curr.right && stack.push(curr.right)
curr.left && stack.push(curr.left)
}
return res
}