Python solution using stack


  • 0

    Here is my solution using stack:

    # Definition for a binary tree node.
    # class TreeNode(object):
    #     def __init__(self, x):
    #         self.val = x
    #         self.left = None
    #         self.right = None
    
    class Solution(object):
        def rightSideView(self, root):
            """
            :type root: TreeNode
            :rtype: List[int]
            """
            if not root: return []
            height = 0
            res = []
            stack = [(root, height)]
            while stack:
                (node, h) = stack.pop()
                if h==len(res): 
                    res.append(node.val)
                    if node.left: stack.append((node.left, h+1))
                    if node.right: stack.append((node.right, h+1))
                else:
                    if node.left:stack.append((node.left, h+1))
                    if node.right: stack.append((node.right, h+1))
            return res
    

Log in to reply
 

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