• 力扣124. 二叉树中的最大路径和


    Problem: 124. 二叉树中的最大路径和

    题目描述

    二叉树中的 路径 被定义为一条节点序列,序列中每对相邻节点之间都存在一条边。同一个节点在一条路径序列中 至多出现一次 。该路径 至少包含一个 节点,且不一定经过根节点。

    路径和 是路径中各节点值的总和。

    给你一个二叉树的根节点 root ,返回其 最大路径和 。
    在这里插入图片描述
    在这里插入图片描述
    在这里插入图片描述

    思路

    按递归的处理思想将该问题分解成如下最小子问题:

    1.分别求取左右子树的最大节点值之和,合并得到整个树的最大节点值之和(每个节点值,我们称其为对最终最大节点值之和的贡献)。
    2.具体的分解处理中:

    2.1空节点的最大贡献值为0;
    2.2非空节点的最大贡献值等于节点值与其子节点中的最大贡献值之和(对于叶节点而言,最大贡献值等于节点值)。

    解题方法

    1.维护一个全局变量 maxSum 存储最大路径和,在递归过程中更新 maxSum 的值;
    2.递归计算左右子节点的最大贡献值,只有在最大贡献值大于 0 时,才会选取对应子节点.(递归函数返回当前节点值加其左右子树的最大节点值之和)
    3.在归的过程中,记录当前节点的最大路径和与maxSum比较,取二者中的较大值并更新maxSum

    复杂度

    时间复杂度:

    O ( n ) O(n) O(n)

    空间复杂度:

    O ( n ) O(n) O(n)

    Code

    /**
     * Definition for a binary tree node.
     * public class TreeNode {
     *     int val;
     *     TreeNode left;
     *     TreeNode right;
     *     TreeNode() {}
     *     TreeNode(int val) { this.val = val; }
     *     TreeNode(int val, TreeNode left, TreeNode right) {
     *         this.val = val;
     *         this.left = left;
     *         this.right = right;
     *     }
     * }
     */
    class Solution {
        //Recode the max path sum
        int maxSum = Integer.MIN_VALUE;
    
        /**
         * Return the max path of a binary tree
         *
         * @param root The root node of a binary tree
         * @return int
         */
        public int maxPathSum(TreeNode root) {
            maxGain(root);
            return maxSum;
        }
    
        /**
         * Get the max path of a binary tree
         *
         * @param node The node of a binary tree
         * @return int
         */
        public int maxGain(TreeNode node) {
            if (node == null) {
                return 0;
            }
    
            /*(1).Recursively calculates the maximum contribution value
             of the left and right child nodes
             (2).Only when the maximum contribution value is greater than 0,
             the corresponding child node is selected
            */
            int leftGain = Math.max(maxGain(node.left), 0);
            int rightGain = Math.max(maxGain(node.right), 0);
    
            //The maximum path sum of a node depends on the value of this node
            // and the maximum contribution of nodes around this node
            int priceNewPath = node.val + leftGain + rightGain;
    
            //Update the max path
            maxSum = Math.max(maxSum, priceNewPath);
    
            return node.val + Math.max(leftGain, rightGain);
        }
    }
    
  • 相关阅读:
    【Javascript】创建对象的几种方式
    HTML+CSS大作业【传统文化艺术耍牙15页】学生个人网页设计作品
    IDEA 2022 创建 Maven Web 项目教程
    C和指针 第15章 输入/输出函数 15.14 流错误函数
    Flink Watermark详解
    题目 1055: 二级C语言-进制转换
    SpringCloud-Feign
    dev-server是怎么跑起来?
    Linux网络编程2-多进程和多线程版本服务器
    【postgresql 基础入门】插入数据的多种方式 单条,多值,查询结果,插入数据冲突处理,批量导入,多种方式让数据插入更灵活
  • 原文地址:https://blog.csdn.net/LNsupermali/article/details/139033471