题解 | #二叉树中的最大路径和#

二叉树中的最大路径和

https://www.nowcoder.com/practice/da785ea0f64b442488c125b441a4ba4a

import java.util.*;

/*
 * public class TreeNode {
 *   int val = 0;
 *   TreeNode left = null;
 *   TreeNode right = null;
 *   public TreeNode(int val) {
 *     this.val = val;
 *   }
 * }
 */

/**
 * NC6 二叉树中的最大路径和
 * @author d3y1
 */
public class Solution {
    private static int result = Integer.MIN_VALUE;

    /**
     * 代码中的类名、方法名、参数名已经指定,请勿修改,直接返回方法规定的值即可
     *
     * 程序入口
     *
     * @param root TreeNode类 
     * @return int整型
     */
    public int maxPathSum (TreeNode root) {
        postorder(root);

        return result;
    }

    /**
     * 递归: 后序遍历
     * @param root
     * @return
     */
    private int postorder(TreeNode root){
        if(root == null){
            return 0;
        }

        // 左分支最大路径值
        int leftMaxVal = postorder(root.left);
        // 右分支最大路径值
        int rightMaxVal = postorder(root.right);
        // 当前节点处最大路径和 当前节点值+左分支最大路径值+右分支最大路径值
        int currSum = root.val;
        if(leftMaxVal > 0){
            currSum += leftMaxVal;
        }
        if(rightMaxVal > 0){
            currSum += rightMaxVal;
        }
        result = Math.max(result, currSum);

        // 当前节点处最大路径值 左分支或右分支或仅取当前节点值
        int currVal = root.val;
        int max = Math.max(leftMaxVal, rightMaxVal);
        if(max > 0){
            currVal += max;
        }

        return currVal;
    }
}

全部评论

相关推荐

27届学院本誓死冲击...:自我评价和校园经历全删了,荣誉经历只留奖学金,项目也全得换都不如外卖
点赞 评论 收藏
分享
评论
点赞
收藏
分享

创作者周榜

更多
牛客网
牛客网在线编程
牛客网题解
牛客企业服务