LeetCode 124.Binary Tree Maximum Path Sum【Java】

Title description

The maximum path sum in the binary tree

AC code

This question is similar to the diameter idea of ​​a binary tree. Enumerate the maximum path sums of the local nodes one by one, and then update the maximum path sum of the entire tree.

/**
 * Definition for a binary tree node.
 * public class TreeNode {
 *     int val;
 *     TreeNode left;
 *     TreeNode right;
 *     TreeNode(int x) { val = x; }
 * }
 */
class Solution {
    int sum=Integer.MIN_VALUE;
    public int maxPathSum(TreeNode root) {
        dfs(root);
        return sum;
    }

    int dfs(TreeNode root){
        if(root==null)
            return 0;
        int left=dfs(root.left);
        int right=dfs(root.right);
		//更新全局的最大路径和
        sum=Math.max(sum,left+right+root.val);
        //求经过当前节点的最大路径和(当前节点值+左/右子树中的最大路径和)
        //如果最大路径和小于<0,没有必要,取0就行了。
        return Math.max(0,root.val+Math.max(left,right));
    }
}
Published 201 original articles · Like9 · Visitors 10,000+

Guess you like

Origin blog.csdn.net/weixin_40992982/article/details/105477051