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.

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



發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章