My simple Python code, No recursion, beat 97.4% python submissions

  • 0

    The basic idea is to use BFS. The goal is to output the last element of each layer. So I keep a queue for the current layer and a queue for the last layer. If the last layer queue is empty, I know the last node I obtain is the last element of the last layer. I add it into the result. The code is below.

    class Solution(object):
        def rightSideView(self, root):
            :type root: TreeNode
            :rtype: List[int]
            if not root:
                return []
            nlOld = [root]
            nlNew = []
            res = []
            while nlOld + nlNew:
                node = nlOld.pop(0)
                if node.left:
                if node.right:
                if not nlOld:
                    nlOld, nlNew = nlNew, []
            return res

Log in to reply

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