Python accepted solution Iterative BFS


  • 0
    K
    class Queue:
        def __init__(self):
            self.d = collections.deque()
        def __len__(self):
            return len(self.d)
        def isEmpty(self):
            if self.d:
                return False 
            else:
                return True 
        def enqueue(self, item):
            self.d.extend([item])
        def dequeue(self):
            if self.d:
                return self.d.popleft()
    class Solution(object):
        def maxDepth(self, root):
            u = root
            if root:
                root.distance = 0
                queue = Queue()
                queue.enqueue(root)
                while not queue.isEmpty():
                    u = queue.dequeue()
                    if u.left:
                        u.left.distance = u.distance + 1
                        queue.enqueue(u.left)
                    if u.right:
                        u.right.distance = u.distance + 1
                        queue.enqueue(u.right)
            else:
                return 0
            return u.distance + 1```

Log in to reply
 

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