My BFS code(Python)


  • 0
    Y

    My BFS code:

    class Solution(object):
        def rightSideView(self, root):
            """
            :type root: TreeNode
            :rtype: List[int]
            """
            queue = []
            if root is None:
                return []
            queue.append([root, 0])#Node and height
            s = set()#Record the height whose node already push_back in ret
            ret = []
            while len(queue) > 0:#BFS
                cur = queue[0][0]
                h = queue[0][1]
                queue = queue[1:]
                if h not in s:
                    s.add(h)
                    ret.append(cur.val)
                if cur.right is not None:
                    queue.append([cur.right, h + 1])
                if cur.left is not None:
                    queue.append([cur.left, h + 1])
            return ret
    

Log in to reply
 

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