给定一棵二叉树,想象自己站在它的右侧,按照从顶部到底部的顺序,返回从右侧所能看到的节点值。
示例:
输入: [1,2,3,null,5,null,4]
输出: [1, 3, 4]
解释:
1 <---
/ \
2 3 <---
\ \
5 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:
vector<int> rightSideView(TreeNode* root) {
queue<pair<TreeNode*,int>> q;
vector<int> vec;
if(root)
q.push(make_pair(root,0));
while(!q.empty())
{
TreeNode* node = q.front().first;
int depth = q.front().second;
q.pop();
if(vec.size() == depth)
vec.push_back(node->val);
else
vec[depth] = node->val;
if(node->left)
q.push(make_pair(node->left,depth+1));
if(node->right)
q.push(make_pair(node->right,depth+1));
}
return vec;
}
};