题目
199. 二叉树的右视图
给定一个二叉树的 根节点 root,想象自己站在它的右侧,按照从顶部到底部的顺序,返回从右侧所能看到的节点值。
示例 1:
输入:root = [1,2,3,null,5,null,4]
输出:[1,3,4]
解释:

示例 2:
输入:root = [1,2,3,4,null,null,null,5]
输出:[1,3,4,5]
解释:

示例 3:
输入:root = [1,null,3]
输出:[1,3]
示例 4:
输入:root = []
输出:[]
提示:
- 二叉树的节点个数的范围是 [0,100]
- -100 <= Node.val <= 100
我的代码(Python)
# Definition for a binary tree node.
# class TreeNode:
# def __init__(self, val=0, left=None, right=None):
# self.val = val
# self.left = left
# self.right = right
class Solution:
def rightSideView(self, root: Optional[TreeNode]) -> List[int]:
result = []
if root is None:
return result
currLvl = [root]
nextLvl = []
while len(currLvl) > 0:
for node in currLvl:
nextLvl.append(node.left) if node.left else None
nextLvl.append(node.right) if node.right else None
result.append(currLvl[-1].val)
currLvl = nextLvl
nextLvl = []
return result
点评
广度优先搜索,只取最右侧的一个结点,这个想法比较容易。
深度优先搜索也可以,这个我没考虑过。用深度优先搜索从右往左也是可行的。
baddif@gmail.com
AI简历优化站
AI求职跟踪器(建设中)
主站(建设中)
相关平台
Github Issues / Notion / Blog