Given a binary tree, imagine yourself standing on the right side of it, return the values of the nodes you can see ordered from top to bottom.
For example:
Given the following binary tree,
1 <--- / \ 2 3 <--- \ \ 5 4 <---
You should return [1, 3, 4]
.
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> res;
if (root==NULL)
return res;
queue<pair<TreeNode*,int>> que;
que.push(make_pair(root,0));
while (!que.empty()){
pair<TreeNode*,int> p1=que.front();
que.pop();
if (que.empty() || p1.second< que.front().second)
res.push_back(p1.first->val);
if (p1.first->left!=NULL)
que.push(make_pair( p1.first->left, p1.second+1 ) );
if (p1.first->right!=NULL)
que.push(make_pair( p1.first->right, p1.second+1) );
}
return res;
}
};