/** * 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[]} */const helper = (node, list) => { if(!node) return list.push(node.val) helper(node.left, list) helper(node.right, list)}var preorderTraversal = function (root) { const list = [] helper(root, list) return list};
/** * 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) { const stack = [], list = [] let node = root while (node || stack.length) { if (node) { list.push(node.val) stack.push(node) node = node.left } else { node = stack.pop() node = node.right } } return list};