美文网首页算法代码
二叉树中的最大路径和

二叉树中的最大路径和

作者: windUtterance | 来源:发表于2020-06-15 22:51 被阅读0次

    题目描述
    给定一个非空二叉树,返回其最大路径和。
    本题中,路径被定义为一条从树中任意节点出发,达到任意节点的序列。该路径至少包含一个节点,且不一定经过根节点。

    示例
    输入: [-10,9,20,null,null,15,7]
    -10
    / \
    9 20
    / \
    15 7
    输出: 42

    Java代码

    /**
     * Definition for a binary tree node.
     * public class TreeNode {
     *     int val;
     *     TreeNode left;
     *     TreeNode right;
     *     TreeNode(int x) { val = x; }
     * }
     */
    class Solution {
        private int max = Integer.MIN_VALUE;
    
        public int helper(TreeNode root) {
            if(root == null) return 0;
    
            int left = Math.max(helper(root.left), 0);
            int right = Math.max(helper(root.right), 0);
    
            //考虑包含当前根节点的最大路径
            max = Math.max(max, root.val + left + right);
    
            //只返回包含当前根节点和左子树或右子树的路径
            return root.val + Math.max(left, right);
        }
    
        public int maxPathSum(TreeNode root) {
            helper(root);
            return max;
        }
    }
    

    相关文章

      网友评论

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

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