Binary Tree Level Order Traversal Solution in Javascript


  • 0
    S
    
    function levelOrderTraversal(root){
      
      let queue=[];
      queue.push(root);
    let result=[];
     
      while(queue.length){
        let arr=[];
        let size=queue.length;
        
        while(size--){
          let node=queue.shift();
          arr.push(node.value);
        if(node.left)
        queue.push(node.left);
        if(node.right)
        queue.push(node.right);
        }
        result.push(arr);
      
        
      }
    return result;
    }
    
    
    function BinaryTreeNode(value) {
        this.value = value;
        this.left  = null;
        this.right = null;
    }
    
    BinaryTreeNode.prototype.insertLeft = function(value) {
        this.left = new BinaryTreeNode(value);
        return this.left;
    };
    
    BinaryTreeNode.prototype.insertRight = function(value) {
        this.right = new BinaryTreeNode(value);
        return this.right;
    }
    
    const root=new BinaryTreeNode(3);
    let A=root.insertLeft(9);
    let B=root.insertRight(20);
    B.insertLeft(15);
    B.insertRight(7);
    
    let result=levelOrderTraversal(root);
    console.log(result);
    
    

Log in to reply
 

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