Given a binary tree, find the maximum path sum.
The path may start and end at any node in the tree.
For example:
Given the below binary tree,
1 / 2 3
Return 6 .
For the tree, we can find the maximum path value that terminates at the root node in its left and right subtree, called the maximum half-path value, and if it is a positive number, you can add them together with the root node value, and if there are negative numbers, discard the value on that side (that is, set to 0). This allows you to find the maximum path value that contains the root node. Then select the largest half path value of the left and right subtree (negative number is set to 0) plus the value of the root node as the new maximum half path value passed to the parent node.
So we can review each subtree recursively, updating a global variable max.
The basic case is: The subtree is null, at which point the maximum path value should be 0.
The code is as follows:
1 intMax;2 Public intmaxpathsum (TreeNode root) {3max = root==NULL? 0: Root.val;4 Findmax (root);5 returnMax;6 }7 Public intFindmax (TreeNode root) {8 if(root==NULL)9 return0;Ten intleft = Math.max (Findmax (root.left), 0); One intright = Math.max (Findmax (root.right), 0); Amax = Math.max (max, left+right+root.val); - returnMath.max (left, right) +Root.val; -}
[Leetcode] [JAVA] Binary Tree Maximum Path Sum