Python non-recursive solution using queue and stack


  • 0
    X
    # python non-recursive solution, using stack
    class Solution(object):
        def maxDepth(self, root):
            if root == None:
                return 0
            stack = [(root, 1)]
            maxDepth = 1
            while stack:
                p, depth = stack[-1]
                stack.pop()
                maxDepth = max(depth, maxDepth)
                if p.right:
                    stack.append((p.right, depth + 1))
                if p.left:
                    stack.append((p.left, depth + 1))
            return maxDepth
    
    # python non-recursive solution, using quuee
    class Solution(object):
        def maxDepth(self, root):
            if root == None:
                return 0
            queue = [(root, 1)]
            maxDepth = 1
            while queue:
                p, depth = queue[0]
                queue.pop(0)
                maxDepth = max(depth, maxDepth)
                if p.right:
                    queue.append((p.right, depth + 1))
                if p.left:
                    queue.append((p.left, depth + 1))
            return maxDepth

Log in to reply
 

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