您的位置:首页 > 其它

LeetCode No.199 Binary Tree Right Side View

2016-11-03 00:48 337 查看
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]
.

====================================================================================
题目链接:https://leetcode.com/problems/binary-tree-right-side-view/

题目大意:求二叉树的右视图

思路:对二叉树进行层次遍历,每次更新,最后一个值就是该层的右视图。

附上代码:

/**
* 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> ans ;
if ( root == NULL )
return ans ;
queue < pair <TreeNode*,int> > q ;
q.push ( make_pair ( root , 0 ) ) ;
while ( !q.empty() )
{
pair <TreeNode*,int> node = q.front() ;
q.pop() ;
TreeNode* temp = node.first ;
int index = node.second ;
if ( ans.size() <= index )
ans.push_back ( 0 ) ;
ans[index] = temp -> val ;
if ( temp -> left )
q.push ( make_pair ( temp -> left , index + 1 ) ) ;
if ( temp -> right )
q.push ( make_pair ( temp -> right , index + 1 ) ) ;
}
return ans ;
}
};
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: