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. const helper = (node, list) => {
    14. if(!node) return
    15. list.push(node.val)
    16. helper(node.left, list)
    17. helper(node.right, list)
    18. }
    19. var preorderTraversal = function (root) {
    20. const list = []
    21. helper(root, list)
    22. return list
    23. };
    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. const stack = [],
    15. list = []
    16. let node = root
    17. while (node || stack.length) {
    18. if (node) {
    19. list.push(node.val)
    20. stack.push(node)
    21. node = node.left
    22. } else {
    23. node = stack.pop()
    24. node = node.right
    25. }
    26. }
    27. return list
    28. };