leetcode -- 515. Find Largest Value in Each Tree Row
程序员文章站
2022-05-20 16:42:11
...
You need to find the largest value in each row of a binary tree.
Example:
Input:
1
/ \
3 2
/ \ \
5 3 9
Output: [1, 3, 9]
来源:力扣(LeetCode)
链接:https://leetcode-cn.com/problems/find-largest-value-in-each-tree-row
著作权归领扣网络所有。商业转载请联系官方授权,非商业转载请注明出处。
我的思路:
1. 用广搜,但是这道题在leetcode上是深搜,我感觉用广搜好解一点,于是选择广搜
2. 因为要记录每一层值,所以在每次进入while循环,先看里面有几个元素,就是每一层的结点个数
3. 然后再在每层中找最大值即可
/**
* 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:
queue<TreeNode*> q; //存放值
vector<int> maxValue;
vector<int> largestValues(TreeNode* root) {
if(root==NULL) return maxValue;
q.push(root);
while(!q.empty()){
int size = q.size();
int maxnV = INT_MIN;
for(int i = 0; i < size; i++){
TreeNode* front = q.front();
int v = front->val; //队头的值
maxnV = max(maxnV, v);
q.pop();
if(front->left) q.push(front->left);
if(front->right) q.push(front->right);
}
maxValue.push_back(maxnV);
}
return maxValue;
}
};
上一篇: 微软封杀WP7中的GPLv3授权程序
下一篇: zoj 1239