Day 23: BST Level-Order Traversal

Sort by

recency

|

426 Discussions

|

  • + 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)
    
  • + 0 comments
    Python3
    
        def levelOrder(self,root):
        #Write your code here
        if root is None:
            return
        queue = [root]
        while queue:
            node = queue.pop(0)
            print(node.data, end=" ")
            if node.left:
                queue.append(node.left)
            if node.right:
                queue.append(node.right)
    
  • + 0 comments

    swift solution

    func levelOrder(root: Node?) -> Void {
            guard let root = root else { return }
            var result: [Int] = []
            var queue:[Node] = []
            queue.append(root)
            while !queue.isEmpty {
                let node = queue.removeFirst()
                if let left = node.left {
                    queue.append(left)
                }
                
                if let right = node.right {
                    queue.append(right)
                }
                result.append(node.data)
            }
            print(result.map { String($0) }.joined(separator: " "))
        	// Complete the function
        } // End of levelOrder function