【leetcode每日刷题】【树遍历】199. Binary Tree Right Side View

mac2024-01-27  34

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 <--- # 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] """ result = [] if root is None: return result queue = [] queue.append(root) front = None while len(queue) != 0: size = len(queue) for i in range(size): front = queue[0] queue.remove(queue[0]) if front.left != None: queue.append(front.left) if front.right != None: queue.append(front.right) if i == size-1: result.append(front.val) return result

使用层次遍历的方法将所有的元素放入队列中,然后将每层的最后一个元素放入结果集合中。

最新回复(0)