199 Binary Tree Right Side View
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].
Solution
/**
* 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;
vector<TreeNode*> tmp(1, root);
while ( tmp.size() != 0 ) {
int ntmp = tmp.size();
res.push_back(tmp[ntmp-1]->val);
vector<TreeNode*> tmp2;
for ( int i = 0; i <= ntmp-1; i++ ) {
if ( tmp[i]->left != NULL ) tmp2.push_back(tmp[i]->left);
if ( tmp[i]->right != NULL ) tmp2.push_back(tmp[i]->right);
}
tmp = tmp2;
}
return res;
}
};