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]
.
/**
* 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:
/*algorithm: level order,
level order, book last element
*/
vector<int> rightSideView(TreeNode* root) {
vector<int>path;
if(!root)return path;
queue<TreeNode*>L;
L.push(root);
while(!L.empty()){
int size = L.size();
TreeNode* t = NULL;
for(int i = 0;i < size;i++){
t = L.front();L.pop();
if(t->left)L.push(t->left);
if(t->right)L.push(t->right);
}
path.push_back(t->val);
}
return path;
}
};