leetcode 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].
树的层序遍历,保留每层的最后一个
/**
* 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<TreeNode*> q;
vector<int> v;
if (root == nullptr) return v;
q.push(root);
while(!q.empty()) {
int x = q.size();
int tmp;
for (int i = 0; i < x; ++i) {
TreeNode* u = q.front();q.pop();
if (u->left != nullptr) q.push(u->left);
if (u->right != nullptr) q.push(u->right);
tmp = u->val;
}
v.push_back(tmp);
}
return v;
}
};
原文地址:http://www.cnblogs.com/pk28/
与有肝胆人共事,从无字句处读书。
欢迎关注公众号:
欢迎关注公众号: