给你二叉树的根节点 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]
/*** 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) {// let res = []// const traversal = (root) => {// if (!root) { return [] }// res.push(root.val)// traversal(root.left);// traversal(root.right)// }// traversal(root)// return res// 迭代版============================================let res = [];if (!root) return res;let stack = [root];while (stack.length) {// 取栈顶const node = stack.pop();res.push(node.val)if (node.right) stack.push(node.right);if (node.left) stack.push(node.left);}return res// 终极模版法=========================================// 前序遍历:中左右// 压栈顺序:右左中// const stack = [], res = [];// if (root) { stack.push(root) }// while (stack.length) {// const node = stack.pop();// if (!node) {// res.push(stack.pop().val);// continue;// }// if (node.right) stack.push(node.right);// if (node.left) stack.push(node.left);// stack.push(node);// stack.push(null);// };// return res};

