Day 23: BST Level-Order Traversal

Sort by

recency

|

430 Discussions

|

  • + 0 comments

    python 3 solution

    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

    Since we can't use Python's collections.deque and the O(1) popleft function, it's actually more effecient to just maintain a pointer to your current location in the list (this avoids the O(N) cost of each pop(0) call).

    Python 3:

        def levelOrder(self,root):
            q = []
            if root is not None:
                q.append(root)
            i = 0
            while i < len(q):
                n = q[i]
                if n.left is not None:
                    q.append(n.left)
                if n.right is not None:
                    q.append(n.right)
                i += 1
            print(" ".join(str(x.data) for x in q))
    
  • + 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]))