题意
实现二叉树的右视图
方法
BFS
代码
/**
* 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) {
vector<int> ans;
if(!root) return ans;
queue<TreeNode*> q;
q.push(root);
while(!q.empty())
{
int n = q.size();
for(int i = 0; i < n; i++)
{
auto node = q.front();
q.pop();
if(i == n-1) //记录每层中最后一个节点的值
{
ans.push_back(node->val);
}
if(node->left) q.push(node->left);
if(node->right) q.push(node->right);
}
}
return ans;
}
};
标签:node,Binary,Right,TreeNode,val,int,LeetCode199,right,left
From: https://www.cnblogs.com/Figure_at_a_Window/p/16913057.html