Tuesday, March 5, 2019

LeetCode 199. Binary Tree Right Side View

'''
Given a binary tree, imagine yourself standing on the right side of it, return the values of the nodes you can see ordered from top to bottom.
'''
# 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 []
       
        nodes = [root]
        result = []
        while nodes:
            result.append(nodes[-1].val)
            temp = []
            for i in nodes:
                if i.left: temp.append(i.left)
                if i.right: temp.append(i.right)
            nodes = temp
        return result

No comments:

Post a Comment