Easy to understand Python Solution (BFS)


  • 0
    T
    class Solution(object):
        def levelOrder(self, root):
            """
            :type root: TreeNode
            :rtype: List[List[int]]
            """
            if root is None:
                return []
                
            current_level = list()
            next_level = list()
            levels = list()
            tmplevel = list()
            
            current_level.append(root)
    
            while current_level:
                # Lets get our node off the front order is important
                node = current_level.pop(0)
                # Save the node at this levels
                tmplevel.append(node.val)
                
                if node.left is not None:
                    next_level.append(node.left)
                if node.right is not None:
                    next_level.append(node.right)
                
                if not current_level:
                    next_level, current_level = current_level, next_level
                    levels.append(tmplevel)
                    tmplevel = list()
            return levels
    

    Modified the answer to the bottom up version of this problem from: https://discuss.leetcode.com/topic/32296/short-python-solution to work for this problem. Very simple change.

     def levelOrder(self, root):
            """
            :type root: TreeNode
            :rtype: List[List[int]]
            """
            result, current_level = [], [root]
            
            while current_level and root:
                result.append([n.val for n in current_level])
                current_level = [n for N in current_level for n in (N.left,N.right) if n]
            return result
    

  • 0
    T
    This post is deleted!

Log in to reply
 

Looks like your connection to LeetCode Discuss was lost, please wait while we try to reconnect.