标签:
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 binary tree
* 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> ans;
if (!root)
return ans;
queue<TreeNode*> q;
q.push(root);
int count = 1;
int num = 0;
while (!q.empty()){
root = q.front();
q.pop();
count--;
if (root->left){
q.push(root->left);
num++;
}
if (root->right){
q.push(root->right);
num++;
}
if (count == 0){
ans.push_back(root->val);
count = num;
num = 0;
}
}
return ans;
}
};
[LeetCode]Binary Tree Right Side View
标签:
原文地址:http://blog.csdn.net/kaitankedemao/article/details/44964509