给你二叉树的根节点 root ,返回它节点值的 前序 遍历。

    示例 1:
    image.png
    输入: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]

    1. /**
    2. * Definition for a binary tree node.
    3. * function TreeNode(val, left, right) {
    4. * this.val = (val===undefined ? 0 : val)
    5. * this.left = (left===undefined ? null : left)
    6. * this.right = (right===undefined ? null : right)
    7. * }
    8. */
    9. /**
    10. * @param {TreeNode} root
    11. * @return {number[]}
    12. */
    13. var preorderTraversal = function (root) {
    14. // let res = []
    15. // const traversal = (root) => {
    16. // if (!root) { return [] }
    17. // res.push(root.val)
    18. // traversal(root.left);
    19. // traversal(root.right)
    20. // }
    21. // traversal(root)
    22. // return res
    23. // 迭代版============================================
    24. let res = [];
    25. if (!root) return res;
    26. let stack = [root];
    27. while (stack.length) {
    28. // 取栈顶
    29. const node = stack.pop();
    30. res.push(node.val)
    31. if (node.right) stack.push(node.right);
    32. if (node.left) stack.push(node.left);
    33. }
    34. return res
    35. // 终极模版法=========================================
    36. // 前序遍历:中左右
    37. // 压栈顺序:右左中
    38. // const stack = [], res = [];
    39. // if (root) { stack.push(root) }
    40. // while (stack.length) {
    41. // const node = stack.pop();
    42. // if (!node) {
    43. // res.push(stack.pop().val);
    44. // continue;
    45. // }
    46. // if (node.right) stack.push(node.right);
    47. // if (node.left) stack.push(node.left);
    48. // stack.push(node);
    49. // stack.push(null);
    50. // };
    51. // return res
    52. };

    image.png