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.
Example:
Input: [1,2,3,null,5,null,4]
Output: [1, 3, 4]
Explanation:
1 <---
/ \
2 3 <---
\ \
5 4 <---
answer:
# Definition for a binary tree node.
# class TreeNode:
# def __init__(self, x):
# self.val = x
# self.left = None
# self.right = None
import queue
class Solution:
def rightSideView(self, root):
"""
:type root: TreeNode
:rtype: List[int]
"""
self.que = queue.Queue()
if root is not None: #注意一开始就传空的进来
self.que.put(root)
res = []
while not self.que.empty():
size = self.que.qsize()
for i in range(size):
head = self.que.get()
if i == size - 1:
num = head.val
if head.left is not None:
self.que.put(head.left)
if head.right is not None:
self.que.put(head.right)
res.append(num)
return res