美文网首页
124. 二叉树中的最大路径和

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

作者: justonemoretry | 来源:发表于2021-08-28 11:08 被阅读0次
image.png

解法

/**
 * 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 {

    public int maxRes = Integer.MIN_VALUE;

    public int maxPathSum(TreeNode root) {
        if (root == null) {
            return 0;
        }
        getMaxLen(root);
        return maxRes;
    }

    public int getMaxLen(TreeNode root) {
        if (root == null) {
            return 0;
        }
        // 获取左右子树上能获取的最大值,负数不取,当0
        int left = Math.max(getMaxLen(root.left), 0);
        int right = Math.max(getMaxLen(root.right), 0);
        int len = left + right + root.val;
        maxRes = Math.max(len, maxRes);
        // 向上联通时,只能取单边,因为每个节点只能经过一次
        return root.val + Math.max(left, right);
    }
}

相关文章

网友评论

      本文标题:124. 二叉树中的最大路径和

      本文链接:https://www.haomeiwen.com/subject/enneiltx.html