• NC_6_TREE_MAX_PATH


    package org.example.interview.practice;
    
    import java.util.Objects;
    
    /**
     * @author xianzhe.ma
     * @date 2021/8/18
     */
    
    public class NC_6_TREE_MAX_PATH {
    
        int maxSum = Integer.MIN_VALUE;
        public int maxPathSum (TreeNode root) {
            // write code here
            maxGain(root);
            return maxSum;
        }
        public int maxGain(TreeNode node) {
            if (node == null) {
                return 0;
            }
    
            // 递归计算左右子节点的最大贡献值
            // 只有在最大贡献值大于 0 时,才会选取对应子节点
            int leftGain = Math.max(maxGain(node.left), 0);
            int rightGain = Math.max(maxGain(node.right), 0);
    
            // 节点的最大路径和取决于该节点的值与该节点的左右子节点的最大贡献值
            int priceNewpath = node.val + leftGain + rightGain;
    
            // 更新答案
            maxSum = Math.max(maxSum, priceNewpath);
    
            // 返回节点的最大贡献值
            return node.val + Math.max(leftGain, rightGain);
        }
    
        public int maxGain2(TreeNode node) {
            if (Objects.isNull(node)) {
                return 0;
            }
    
            int left = Math.max(maxGain2(node.left),0);
            int right = Math.max(maxGain2(node.right),0);
    
            int currentMax = node.val + left + right;
    
            maxSum = Math.max(maxSum, currentMax);
    
            return node.val + Math.max(left, right);
        }
    
        public class TreeNode {
            int val = 0;
            TreeNode left = null;
            TreeNode right = null;
        }
    
    }
  • 相关阅读:
    请教提高上百万行数据insert速度的“经典”方法
    poj1411
    poj1422
    poj1661
    poj1664
    poj1405
    交往艺术与沟通技巧[推荐]
    不可不听的10个职场故事
    也谈如何“领导”你的领导
    十个让爱情稳固的经典好习惯
  • 原文地址:https://www.cnblogs.com/juniorMa/p/15879365.html
Copyright © 2020-2023  润新知