Python solution use level to traverse


  • 1
    A
    class Solution:
    # @param {TreeNode} root
    # @return {integer[]}
    def rightSideView(self, root):
        self.ans = []
        self.dfs(root, 1)
        return self.ans
    
    def dfs(self, root, level):
        if not root:
            return
        if len(self.ans) < level:
            self.ans.append(root.val)
        self.dfs(root.right, level + 1)
        self.dfs(root.left, level + 1)

Log in to reply
 

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