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

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

单选题

题目描述

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

1 struct TreeNode {
2  int val;
3  TreeNode* left;
4  TreeNode* right;
5  TreeNode(int x): val(x), left(nullptr), right(nullptr) {}
6 };
7
8 vector<int> rightSideView(TreeNode* root) {
9  unordered_map<int, int> rightmostValueAtDepth;
10  int max_depth = -1;
11
12  queue<TreeNode*> nodeQueue;
13  queue<int> depthQueue;
14  nodeQueue.push(root);
15  depthQueue.push(0);
16
17  while (!nodeQueue.empty()) {
18   TreeNode* node = nodeQueue.front(); nodeQueue.pop();
19   int depth = depthQueue.front(); depthQueue.pop();
20
21   if (node != NULL) {
22    max_depth = max(max_depth, depth);
23
24    rightmostValueAtDepth[depth] = node->val;
25
26    nodeQueue.push(node->left);
27    nodeQueue.push(node->right);
28
29    depthQueue.push(________);
30    depthQueue.push(________);
31   }
32  }
33
34  vector<int> rightView;
35  for (int depth = 0; ________; ++depth) {
36   rightView.push_back(rightmostValueAtDepth[depth]);
37  }
38  return rightView;
39 };


选项(单选)