Day 23: BST Level-Order Traversal

Sort by

recency

|

428 Discussions

|

  • + 0 comments

    JavaSCript

    this.levelOrder = function(root) {
        if (!root) {
            return;
        }
    
        const queue = [];
        queue.push(root);
    
        while (queue.length > 0) {
            const node = queue.shift();
            process.stdout.write(node.data + " ");
    
            if (node.left) {
                queue.push(node.left);
            }
            if (node.right) {
                queue.push(node.right);
            }
        }
    };
    
  • + 0 comments

    in JS

    // Start of function levelOrder
        this.levelOrder = function(root) {
        if (!root) return;
    
            const queue = [];
            queue.push(root);
    
            while (queue.length > 0) { 
                const levelSize = queue.length; 
    
            for (let i = 0; i < levelSize; i++) { 
            const node = queue.shift(); 
            process.stdout.write(node.data + ' '); 
    
            if (node.left) queue.push(node.left); 
            if (node.right) queue.push(node.right);  
            }
            }  
        }; // End of function levelOrder
    
  • + 0 comments
     def levelOrder(self,root):
        queue = [root]
        for item in queue:
            if item.left:
                queue.append(item.left)
            if item.right:
                queue.append(item.right)
        print(" ".join([str(i.data) for i in queue]))
    
  • + 0 comments
    void levelOrder(Node * root){
     vector<Node*> oQ;
     
     if (nullptr != root) {
      oQ.push_back(root);
    
      for(int i=0; i<oQ.size(); i++) {
       cout<<oQ[i]->data<<" ";
    
       if (nullptr != oQ[i]->left)
        oQ.push_back(oQ[i]->left);
    
       if (nullptr != oQ[i]->right)
        oQ.push_back(oQ[i]->right);
      }
     }
    }
    
  • + 1 comment
    def levelOrder(self,root):
        #Write your code here
        queue = [root]
    
        while queue:
            node = queue.pop(0)  # Pop from the front
    
            print(f"{node.data}", end=" ")
    
            for new in [node.left, node.right]:
                if new:
                    queue.append(new)