199. 二叉树的右视图(C++题解含VS可运行源程序)
1.题解
层序遍历
- 层次遍历,取每一层的最右值,就ok了。
- 超级简单。
2.力扣C++源码
/**
* 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) {
//层次遍历的方法,只要取每一层的最右值
//参考102. 二叉树的层序遍历
if (!root)return {
};
vector<int> temp;
vector<int> res;
queue<TreeNode*> store;
store.push(root);
int remaining = 1;
int nextlevel = 0;
while (!store.empty()) {
TreeNode* node = store.front();
store.pop();
remaining--;
temp.push_back(node->val);
if (node->left) {
store.push(node->left);
nextlevel++;
}
if (node->right) {
store.push(node