给你二叉树的根节点 root ,返回它节点值的 前序 遍历。
示例 1:
输入: root = [1,null,2,3]
输出: [1,2,3]
示例 2:
输入: root = []
输出: []
题解:
/**
* Definition for a binary tree node.
* function TreeNode(val, left, right) {
* this.val = (val===undefined ? 0 : val)
* this.left = (left===undefined ? null : left)
* this.right = (right===undefined ? null : right)
* }
*/
/**
* @param {TreeNode} root
* @return {number[]}
*/
var preorderTraversal = function (root) {
// 前序遍历:中、左、右
// 方法一:递归
// inorder(root) 递归头节点
// inorder(root.left) 递归左节点
// inorder(root.right) 递归右节点
const stack = []
const inorder = (root) => {
if (!root) return
stack.push(root.val)
inorder(root.left)
inorder(root.right)
}
inorder(root)
return stack
// 方法二:迭代
// 先头节点入栈
// 1、从栈内弹出节点cur
// 2、打印cur
// 3、先把cur右节点入栈,再把左节点入栈(左、右节点存在的情况)
// 4、重复1=>2=>3
if(!root) return []
const stack = []
const res = []
stack.push(root) // 头节点入栈
while(stack.length){
let head = stack.pop() // 当前节点出栈
res.push(head.val) // res存入先序结果
head.right && stack.push(head.right) // 有右节点 右节点入栈
head.left && stack.push(head.left) // 有左节点 左节点入栈
}
return res
};