Simple python, BFS and Iterate


  • 0
    Y
    class Solution(object):
        def rightSideView(self, root):
            if not root:return []
            queue=collections.deque([(root,1)])
            dic=collections.defaultdict(list)
            while queue:
                root,level=queue.popleft()
                if not root:
                    continue
                dic[level].append(root.val)
                if root.left:
                    queue.append((root.left,level+1))
                if root.right:
                    queue.append((root.right,level+1))
            res=[]
            for key in sorted(dic):
                res.append(dic[key][-1])
            return res
    #210 / 210 test cases passed.
    #Status: Accepted
    #Runtime: 45 ms
    

Log in to reply
 

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