Python Code ( DFS recursively, DFS + Stack )


  • 0
    R
    # DFS recursively 
    class Solution(object):
        def levelOrder(self, root):
            """
            :type root: TreeNode
            :rtype: List[List[int]]
            """
            ret = [ ]
            self.helper(root, 0, ret)
            return ret         
            
        def helper(self, root, level, ret):
            if root:
                if len(ret) < level+1:
                    ret.append([ ]) 
                ret[level].append(root.val)
                self.helper(root.left,  level+1, ret)   
                self.helper(root.right, level+1, ret) 
                
                
    # DFS + stack             
    class Solution(object):
        def levelOrder(self, root):
            """
            :type root: TreeNode
            :rtype: List[List[int]]
            """
            stack, ret = [(root, 0)], [ ]      
            while stack:
                node, level = stack.pop( )  
                if root:
                    if len(ret) < level+1:
                        ret.append([ ])
                    ret[level].append(node.val)
                    stack.append((node.right, level+1))
                    stack.append((node.left, level+1))
    
            return ret     
    

Log in to reply
 

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