Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Error in Level Order Traversal of Binary Tree

What mistake have i done here ?

def levelOrder(root):
#Write your code here
que = []
que.append(root)
while que != []:
    coot = que.pop()
    print(coot.data,end=" ")

    if coot.left is not None:
        que.append(coot.left)

    if coot.right is not None:
        que.append(coot.right)

OutPut Expected:1 2 5 3 6 4

MY_output: 1 2 5 6 3 4

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>Solution :

You are appending nodes to end end of the list que(using append()). And also removing the nodes from the end of the list que(using list.pop()), this would not preserve the order, so for something like

             1
            /  \
           2    3 
          / \   / \
         4   5  6  7 

After first iteration would have que=[2, 3], and then you would pop 3 first instead of 2, which is incorrect. Instead, you should be popping 2, popping from the left(since you are appending the new nodes to the right).

So replacing coot = que.pop() with coot = que.pop(0) in your existing code should fix the issue. But note that list.pop(0) is a O(n) operation python. So I would suggest using collections.deque instead.

With deque, your code can be –

from collections import deque
def levelOrder(root):
    #Write your code here
    que = deque()
    que.append(root)
    while que != []:
        coot = que.popleft()
        print(coot.data,end=" ")

        if coot.left is not None:
            que.append(coot.left)

        if coot.right is not None:
            que.append(coot.right)
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading