您的位置:首页 > 编程语言 > Go语言

二叉树层序遍历应用之Binary Tree Right Side View

2015-05-07 17:22 411 查看
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]
.

Solutions:

易想到求的是每层中最右的一个节点。

二叉树层序遍历过程中,每次循环开始时,队列中存放的刚好是将要访问的一层的节点。

/**
* 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> result;
if(root==NULL){
return result;
}
queue<TreeNode*> Q;
Q.push(root);
TreeNode *right;
while(!Q.empty()) {
int Qsize=Q.size();
for(int i=0; i<Qsize; ++i) {
right=Q.front();
Q.pop();
if(right->left != NULL){
Q.push(right->left);
}
if(right->right != NULL){
Q.push(right->right);
}
}
result.push_back(right->val);
}
}
};
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息