Find Largest Value in Each Tree Row问题及解法
2017-08-21 10:48
337 查看
问题描述:
You need to find the largest value in each row of a binary tree.
示例:
问题分析:
分析可知,此类题可用广度优先遍历求解。
过程详见代码:
/**
* 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> largestValues(TreeNode* root) {
queue<TreeNode*> q;
vector<int> res;
if (root == nullptr) return res;
q.push(root);
int m;
while (!q.empty())
{
int size = q.size();
m = INT_MIN;
for (int i = 0; i < size; i++)
{
TreeNode * t = q.front();
m = max(m, t->val);
q.pop();
if (t->left) q.push(t->left);
if (t->right) q.push(t->right);
}
res.emplace_back(m);
}
return res;
}
};
You need to find the largest value in each row of a binary tree.
示例:
Input: 1 / \ 3 2 / \ \ 5 3 9 Output: [1, 3, 9]
问题分析:
分析可知,此类题可用广度优先遍历求解。
过程详见代码:
/**
* 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> largestValues(TreeNode* root) {
queue<TreeNode*> q;
vector<int> res;
if (root == nullptr) return res;
q.push(root);
int m;
while (!q.empty())
{
int size = q.size();
m = INT_MIN;
for (int i = 0; i < size; i++)
{
TreeNode * t = q.front();
m = max(m, t->val);
q.pop();
if (t->left) q.push(t->left);
if (t->right) q.push(t->right);
}
res.emplace_back(m);
}
return res;
}
};
相关文章推荐
- LeetCode算法问题17 —— Find Largest Value in Each Tree Row
- 515[Medium]:Find Largest Value in Each Tree Row
- leetcode515: Find Largest Value in Each Tree Row
- [LeetCode]515 Find Largest Value in Each Tree Row(dfs)
- Tree——Find Largest Value in Each Tree Row
- Find Largest Value in Each Tree Row
- LeetCode #515: Find Largest Value in Each Tree Row
- leetcode515 Find Largest Value In Each Tree Row Java
- 第十二周算法分析与设计: 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
- Find Largest Value in Each Tree Row
- 算法分析与设计丨第三周丨LeetCode(6)——Find Largest Value in Each Tree Row(Medium)
- Find Largest Value in Each Tree Row
- leetcode 515 Find Largest Value in Each Tree Row C++
- 【LeetCode515 Find Largest Value in Each Tree Row】二叉树每行的最大值
- [leetcode 515]Find Largest Value in Each Tree Row
- LeetCode 515 Find Largest Value in Each Tree Row(二叉树层序遍历)
- LeetCode Find Largest Value in Each Tree Row