前往小程序,Get更优阅读体验!
立即前往
首页
学习
活动
专区
工具
TVP
发布
社区首页 >专栏 >【leetcode刷题】T139-在每个树行中找最大值

【leetcode刷题】T139-在每个树行中找最大值

作者头像
木又AI帮
发布2019-08-12 15:01:44
9670
发布2019-08-12 15:01:44
举报
文章被收录于专栏:木又AI帮

木又连续日更第95天(95/100)


木又的第139篇leetcode解题报告

二叉树类型第29篇解题报告

leetcode第515题:在每个树行中找最大值

https://leetcode-cn.com/problems/find-largest-value-in-each-tree-row/


【题目】

您需要在二叉树的每一行中找到最大的值。

代码语言:javascript
复制
示例:
输入: 
          1
         / \
        3   2
       / \   \  
      5   3   9 
输出: [1, 3, 9]

【思路】

本题和【T138-找树左下角的值】较为类似,同样有两种解法:一是层次遍历,得到每一层元素,再找到每一层的最大值;二是中序遍历(前序遍历和后序遍历也可以),存储节点的值,并标记其层数,当某一层某个节点的值大于存储的值时,进行替换。

昨天分享的是第二种解法,今天分享第一种解法。

【代码】

python版本

代码语言:javascript
复制
# 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++版本

代码语言:javascript
复制
/**
 * 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;
    }
};
本文参与 腾讯云自媒体同步曝光计划,分享自微信公众号。
原始发表:2019-08-10,如有侵权请联系 cloudcommunity@tencent.com 删除

本文分享自 木又AI帮 微信公众号,前往查看

如有侵权,请联系 cloudcommunity@tencent.com 删除。

本文参与 腾讯云自媒体同步曝光计划  ,欢迎热爱写作的你一起参与!

评论
登录后参与评论
0 条评论
热度
最新
推荐阅读
领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档