测评会员优惠活动进行中 · 开通 VIP,有效期内测评不限次 VIP 优惠中 · 测评不限次 立即查看

A60971. 给定一棵二叉树,采用广度优先搜索 (BFS) 算法,返回右视图所有节点的值。其中右视图定义为:二叉树的右视图是从树的右侧看过去时可见的节点集合,即右视图中的每个节点都是某一层中最右侧的节点。1 class TreeNode

单选题

题目描述

给定一棵二叉树,采用广度优先搜索 (BFS) 算法,返回右视图所有节点的值。其中右视图定义为:二叉树的右视图是从树的右侧看过去时可见的节点集合,即右视图中的每个节点都是某一层中最右侧的节点。

1 class TreeNode:
2 def __init__(self, x):
3   self.val = x
4   self.left = None
5   self.right = None
6
7 def rightSideView(root):
8  rightmost_value_at_depth = {}
9  max_depth = -1
10
11  node_queue = []
12  depth_queue = []
13  node_queue.append(root)
14  depth_queue.append(0)
15
16  while node_queue:
17   node = node_queue.pop(0)
18   depth = depth_queue.pop(0)
19
20   if node is not None:
21    max_depth = max(max_depth, depth)
22    rightmost_value_at_depth[depth] = node.val
23
24    node_queue.append(node.left)
25    node_queue.append(node.right)
26
27    # (1)
28    depth_queue.append(__________)
29    depth_queue.append(__________)
30
31
32  right_view = []
33  # (2) 补全
34  for depth in range(____________):
35   right_view.append(rightmost_value_at_depth[depth])
36
37  return right_view
38
39 if __name__ == "__main__":
40  root = TreeNode(1)
41  root.left = TreeNode(2)
42  root.right = TreeNode(3)
43  root.left.right = TreeNode(5)
44  root.right.right = TreeNode(4)
45
46  print(rightSideView(root))

选项(单选)