Python based on Dictionary and BFS

  • 0
    def rightSideView(self, root):
        if not root: return []
        if not root.left and not root.right: return [root.val]
        # BFS
        depth, curr_depth = 0, 0
        queue = collections.deque([(root, depth)])
        dic = dict()
        while queue:
            curr, curr_depth = queue.popleft()
            dic[curr_depth] = curr.val
            if curr.left: 
                queue.append((curr.left, curr_depth + 1))
            if curr.right:
                queue.append((curr.right, curr_depth + 1))   
        return dic.values()

Log in to reply

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