199. 二叉树的右视图
给定一棵二叉树,想象自己站在它的右侧,按照从顶部到底部的顺序,
返回从右侧所能看到的节点值。
示例:
输入: [1,2,3,null,5,null,4]
输出: [1, 3, 4]
解释:
1 <---
/ \
2 3 <---
\ \
5 4 <---
这道题和之前的二叉树层次遍历是类似的,只不过,在这里我们只需要将每一层的最后一个数字加入到输出中,而不需要每个数字都加入。
# @lc code=start
# 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 []
queue = collections.deque()
queue.append(root)#创建双向队列
out = []
res = None
while queue:
for _ in range(len(queue)):#每次根据队列内的元数个数确定循环次数
node = queue.popleft()#从队列的左边弹出一个节点
if node.left: queue.append(node.left)#查看左右节点是否存在,存在就加入到队列中
if node.right: queue.append(node.right)
res = node.val#找到每一层的最后一个值
out.append(res)#每层最后一个值加入到输出中
res = None#初始化res
return out
# @lc code=end
使用DFS的代码如下:
- 每次设置一个depth深度值,每次递归的时候深度值加一,如果当前列表内长度小于深度值,就加入列表,因为这里时右子树的DFS在前面,所以首先加入的时右子树,如果右子树不存在,才会加入左子树。
class Solution:
def rightSideView(self, root: TreeNode) -> List[int]:
res = []
def dfs(root, depth):
if not root:return
if len(res) < depth:#这里限定了每一层只能加入一个节点
res.append(root.val)
dfs(root.right, depth+1)#先加入的是右子树的右节点
dfs(root.left, depth+1)
dfs(root,1)
return res