Preorder traversal (javascript)


  • 0
    G
     * Definition for a binary tree node.
     * function TreeNode(val) {
     *     this.val = val;
     *     this.left = this.right = null;
     * }
     */
    /**
     * @param {TreeNode} root
     * @return {number[]}
     */
    var vals = [];
    
    var recur = function(node) {
      if(node.val) { vals.push(node.val) }
      if(node.left) { recur(node.left) }
      if(node.right) { recur(node.right) }
    };
    
    var preorderTraversal = function(root) {
        vals = [];
    
        if (root) {
          recur(root);  
        }
    
        return vals;
    };
    

Log in to reply
 

Looks like your connection to LeetCode Discuss was lost, please wait while we try to reconnect.