您的位置:首页 > 产品设计 > UI/UE

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.

示例:

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;
}
};
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: