Binary Tree Right Side View
2015-10-16 11:17
381 查看
题目:
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,
You should return
看到这道题就想到了广度优先遍历,使用队列实现
不过中间出现了一个问题,就是怎么该标识每一层的结束,当时想到用二个队列,看了别人的代码后,才发现用size即可。。。
/**
* 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> ret;
queue<TreeNode*> q;
if(root!=NULL) q.push(root);
while(!q.empty()){
int k=q.size();
for(int i=0;i<k;++i)
{
TreeNode* tmp=q.front();q.pop();
if(i==k-1) ret.push_back(tmp->val);
if(tmp->left!=NULL) q.push(tmp->left);
if(tmp->right!=NULL) q.push(tmp->right);
}
}
return ret;
}
};
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].
看到这道题就想到了广度优先遍历,使用队列实现
不过中间出现了一个问题,就是怎么该标识每一层的结束,当时想到用二个队列,看了别人的代码后,才发现用size即可。。。
/**
* 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> ret;
queue<TreeNode*> q;
if(root!=NULL) q.push(root);
while(!q.empty()){
int k=q.size();
for(int i=0;i<k;++i)
{
TreeNode* tmp=q.front();q.pop();
if(i==k-1) ret.push_back(tmp->val);
if(tmp->left!=NULL) q.push(tmp->left);
if(tmp->right!=NULL) q.push(tmp->right);
}
}
return ret;
}
};
相关文章推荐
- leetcode 179 Largest Number
- leetcode 24 Swap Nodes in Pairs
- leetcode 2 Add Two Numbers 方法1
- leetcode 2 Add Two Numbers 方法2
- [LeetCode]47 Permutations II
- [LeetCode]65 Valid Number
- [LeetCode]123 Best Time to Buy and Sell Stock III
- [LeetCode] String Reorder Distance Apart
- [LeetCode] Sliding Window Maximum
- [LeetCode] Find the k-th Smallest Element in the Union of Two Sorted Arrays
- [LeetCode] Determine If Two Rectangles Overlap
- [LeetCode] A Distance Maximizing Problem
- leetcode_linearList
- leetcode_linearList02
- 021-Merge Two Sorted Lists(合并两个排好序的单链表);leetcode
- LeetCode[Day 1] Two Sum 题解
- LeetCode[Day 2] Median of Two Sorted Arrays 题解
- LeetCode[Day 3] Longest Substring Without... 题解
- LeetCode [Day 4] Add Two Numbers 题解
- LeetCode [Day 5] Longest Palindromic Substring 题解