199. Binary Tree Right Side View
题目描述
假设站在二叉树右侧, 求能看到的节点.
解题思路
层序遍历, 每层的最后一个就是能被看到的.
代码
Python
# Definition for a binary tree node.
# class TreeNode:
# def __init__(self, x):
# self.val = x
# self.left = None
# self.right = None
class Solution:
def rightSideView(self, root: TreeNode) -> List[int]:
if not root:
return []
if root.left == None and root.right == None:
return [root.val]
# 层序遍历的最后一个
queue = [root]
cur = []
res = [root.val]
while queue:
node = queue.pop(0)
if node.left: cur.append(node.left)
if node.right: cur.append(node.right)
if not queue:
queue += cur
if cur: res.append(cur[-1].val)
cur = []
return res