给定一棵二叉树,想象自己站在它的右侧,按照从顶部到底部的顺序,返回从右侧所能看到的节点值。
样例
样例1
输入: {1,2,3,#,5,#,4}
输出: [1,3,4]
说明:
1
/ \
2 3
\ \
5 4
样例2
输入: {1,2,3}
输出: [1,3]
说明:
1
/ \
2 3
/**
* Definition of TreeNode:
* class TreeNode {
* public:
* int val;
* TreeNode *left, *right;
* TreeNode(int val) {
* this->val = val;
* this->left = this->right = NULL;
* }
* }
*/
class Solution {
public:
/**
* @param root: the root of the given tree
* @return: the values of the nodes you can see ordered from top to bottom
*/
vector<int> rightSideView(TreeNode * root) {
// write your code here
vector<int> ret;
//vector<vector<int>> result;
if (root == NULL) {
return ret;
}
queue<TreeNode *> Q;
Q.push(root);
while (!Q.empty()) {
int size = Q.size();
//vector<int> level;
for (int i = 0; i < size; i++) {
TreeNode *head = Q.front(); Q.pop();
if(i == size -1)
ret.push_back(head->val);
//level.push_back(head->val);
if (head->left != NULL) {
Q.push(head->left);
}
if (head->right != NULL) {
Q.push(head->right);
}
}
//result.push_back(level);
}
return ret;
}
};