Day 23: BST Level-Order Traversal

  • + 17 comments

    For Python coders, here's how you can code it "pythonic" way:

    def levelOrder(self,root):
        queue = [root] if root else []
        
        while queue:
            node = queue.pop()
            print(node.data, end=" ")
            
            if node.left: queue.insert(0,node.left)
            if node.right: queue.insert(0,node.right)
    

    This post is targeted towards aspiring "python programmers".

    Code in python usually looks elegant and clear. "High-readability" is one of the reasons behind its growing popularity. Though, at times, you'll find python-version of code looking worse. This mostly happens if the code is written by inexperienced python programmer (usually coming from other languages). For such times, I encourage you to find the "pythonic way" of coding it instead of using "plain translation from other languages". It will surely benefit you in the long run.

    Just to give an example, a pythonista would always use while queue: instead of while queue != None :, former being far clear and concise. I hope this post gives some tips regarding "python-way" of coding and encourages you to find better ways to code.


    Informative Tweets for Inquisitive Minds