Tree——Find Largest Value in Each Tree Row
2017-03-12 10:49
337 查看
问题描述:
你需要在二叉树的每一行中找到最大值,并将所有的最大值放在vector中作为返回值。解题思路:
从根节点开始,依次将每一层的节点从左到右放入vector,current指向当前访问的节点,last指向当前层的最后一个节点。然后把每一层的所有节点值放入一个vector,访问当前层结束后,找出最大的元素放入result中。源代码如下:
class Solution {public:
vector<int> largestValues(TreeNode* root) {
vector<int> result;
if(root!=NULL)
{
vector<TreeNode* > vec;
vec.push_back(root);
int current=0;
int last=1;
while(current<vec.size())
{
last=vec.size();
vector<int> vals;
for(;current<last;current++)
{
vals.push_back(vec[current]->val);
if(vec[current]->left!=NULL) vec.push_back(vec[current]->left);
if(vec[current]->right!=NULL) vec.push_back(vec[current]->right);
}
int max=vals[0];
for(int i=1;i<vals.size();i++)
{
if(vals[i]>max) max=vals[i];
}
result.push_back(max);
}
}
return result;
}
};
相关文章推荐
- 算法分析与设计丨第三周丨LeetCode(6)——Find Largest Value in Each Tree Row(Medium)
- Find Largest Value in Each Tree Row
- LeetCode算法问题17 —— Find Largest Value in Each Tree Row
- LeetCode——Find Largest Value in Each Tree Row
- 【LEETCODE】 Find Largest Value in Each Tree Row javascript实现
- [LeetCode]515 Find Largest Value in Each Tree Row(dfs)
- Find Largest Value in Each Tree Row
- Find Largest Value in Each Tree Row宽度优先遍历算法详解
- LeetCode #515: Find Largest Value in Each Tree Row
- Find Largest Value in Each Tree Row
- Find Largest Value in Each Tree Row
- 【LeetCode515 Find Largest Value in Each Tree Row】二叉树每行的最大值
- 【LeetCode】Find Largest Value in Each Tree Row 解题报告
- Find Largest Value in Each Tree Row
- Find Largest Value in Each Tree Row(找出一棵树每一行的最大值)
- LeetCode Find Largest Value in Each Tree Row
- Find Largest Value in Each Tree Row
- 515[Medium]:Find Largest Value in Each Tree Row
- [LeetCode] Find Largest Value in Each Tree Row 找树每行最大的结点值
- leetcode515 Find Largest Value In Each Tree Row Java