题意:求出二叉树每一层最右边的节点值。
题解:BFS.
/**
* Definition for a binary tree node.
* struct TreeNode {
* int val;
* TreeNode *left;
* TreeNode *right;
* TreeNode(int x) : val(x), left(NULL), right(NULL) {}
* };
*/
class Solution {
public:
vector<int> rightSideView(TreeNode* root) {
vector<int> ans;
queue<TreeNode*> q;
if(root == NULL) return ans;
q.push(root);
while(!q.empty())
{
int n = q.size();
for(int i = 1; i <= n - 1; i++)
{
TreeNode* now = q.front();
q.pop();
if(now->left) q.push(now->left);
if(now->right) q.push(now->right);
}
TreeNode* now = q.front();
q.pop();
if(now->left) q.push(now->left);
if(now->right) q.push(now->right);
ans.push_back(now->val);
}
return ans;
}
};