题目大意:给出一个二叉树,假设你站在二叉树的右边,输出你能看得到的节点。
算法思想
按层序遍历二叉树,输出每层中最右边的节点即可。
代码如下:
/**
* 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> res;
if(root==NULL) return res;
queue<pair<TreeNode*,int>> Q;
Q.push(make_pair(root,1));
int level=1;
int value=root->val;
while(!Q.empty()){
pair<TreeNode*,int> tmp=Q.front();
Q.pop();
if(tmp.second==level)
value=tmp.first->val;
else{
res.push_back(value);
value=tmp.first->val;
level=tmp.second;
}
if(tmp.first->left!=NULL)
Q.push(make_pair(tmp.first->left,tmp.second+1));
if(tmp.first->right!=NULL)
Q.push(make_pair(tmp.first->right,tmp.second+1));
}
res.push_back(value);
return res;
}
};