木又连续日更第95天(95/100)
木又的第139篇leetcode解题报告
二叉树
类型第29篇解题报告
leetcode第515题:在每个树行中找最大值
https://leetcode-cn.com/problems/find-largest-value-in-each-tree-row/
【题目】
您需要在二叉树的每一行中找到最大的值。
示例:
输入:
1
/ \
3 2
/ \ \
5 3 9
输出: [1, 3, 9]
【思路】
本题和【T138-找树左下角的值】较为类似,同样有两种解法:一是层次遍历,得到每一层元素,再找到每一层的最大值;二是中序遍历(前序遍历和后序遍历也可以),存储节点的值,并标记其层数,当某一层某个节点的值大于存储的值时,进行替换。
昨天分享的是第二种解法,今天分享第一种解法。
【代码】
python版本
# Definition for a binary tree node.
# class TreeNode(object):
# def __init__(self, x):
# self.val = x
# self.left = None
# self.right = None
class Solution(object):
def largestValues(self, root):
"""
:type root: TreeNode
:rtype: List[int]
"""
if not root:
return []
# 层次遍历,找到最大值
p = [root]
q = []
res = []
val = root.val
while p or q:
if not p:
p = copy.copy(q)
q = []
res.append(val)
val = p[0].val
cur = p.pop(0)
val = max(val, cur.val)
# 加入下一层节点
if cur.left:
q.append(cur.left)
if cur.right:
q.append(cur.right)
# 最后一次循环,p、q皆为空
res.append(val)
return res
C++版本
/**
* 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) {
vector<int> res;
if(!root)
return res;
queue<TreeNode*> p;
queue<TreeNode*> q;
p.push(root);
int val = root->val;
TreeNode* cur = NULL;
while(!p.empty() || !q.empty()){
if(p.empty()){
while(!q.empty()){
p.push(q.front());
q.pop();
}
res.push_back(val);
// 新的一层,改变初始值
val = p.front()->val;
}
cur = p.front();
p.pop();
val = max(val, cur->val);
if(cur->left)
q.push(cur->left);
if(cur->right)
q.push(cur->right);
}
// 最后一次遍历,p、q都为空,未能添加最后一层的最大元素
res.push_back(val);
return res;
}
};
扫码关注腾讯云开发者
领取腾讯云代金券
Copyright © 2013 - 2025 Tencent Cloud. All Rights Reserved. 腾讯云 版权所有
深圳市腾讯计算机系统有限公司 ICP备案/许可证号:粤B2-20090059 深公网安备号 44030502008569
腾讯云计算(北京)有限责任公司 京ICP证150476号 | 京ICP备11018762号 | 京公网安备号11010802020287
Copyright © 2013 - 2025 Tencent Cloud.
All Rights Reserved. 腾讯云 版权所有