广度优先搜索
- 思路:
- 使用广度优先搜索,那么每层最后一次遍历的节点就是最右视图的节点;
- 广度优先搜索模板:
- 完整代码:
/**
* Definition for a binary tree node.
* struct TreeNode {
* int val;
* TreeNode *left;
* TreeNode *right;
* TreeNode() : val(0), left(nullptr), right(nullptr) {}
* TreeNode(int x) : val(x), left(nullptr), right(nullptr) {}
* TreeNode(int x, TreeNode *left, TreeNode *right) : val(x), left(left), right(right) {}
* };
*/
class Solution {
public:
vector<int> rightSideView(TreeNode* root) {
std::vector<int> result;
if (root == nullptr) {
return result;
}
std::queue<TreeNode*> nq;
nq.push(root);
while (!nq.empty()) {
int levelSize = nq.size();
for (int idx = 0; idx < levelSize; ++idx) {
auto node = nq.front();
nq.pop();
if (idx == levelSize - 1) {
result.push_back(node->val);
}
if (node->left) {
nq.push(node->left);
}
if (node->right) {
nq.push(node->right);
}
}
}
return result;
}
};