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 .
Test instructions: To find the maximum value of the two-point path of any unicom in a binary tree.
Idea: Depth traversal of the two-fork tree.
There are three scenarios with the maximum and path:
1. In the root.left subtree; 2. In the root.right subtree; 3. Contains the root node, part of the Root.left, and the other part in Root.right.
We record two data, the global variable Max represents the global maximum value, and the local variable Currentmax represents the maximum value of the path through the current root node . As shown
In a subtree with a root of-9, max=7, currentmax= ( -9+7) =-2;
In a subtree with a root node of 3, max=11,currentmax= (6+3) = 9;
In a subtree with a root node of 1, max=11, currentmax= (1+9) = 10;
Finally, the result we want is max;
The return value of the recursive method needs to be noted. The code is as follows:
1 Public intmaxpathsum (TreeNode root) {2 if(Root = =NULL)3 return0;4 Maxpathsumhelper (root);5 return This. Max;6 }7 8 Public intMax =Integer.min_value;9 Public intmaxpathsumhelper (TreeNode root) {Ten if(Root = =NULL) One return0; A intLeftmax = 0; - intRightmax = 0; - the intReturnValue =Root.val; -Max =Math.max (Root.val, max); - if(Root.left! =NULL) { -Leftmax =Maxpathsumhelper (root.left); +max = Math.max (max, Math.max (Leftmax, leftmax+root.val)); -returnvalue = Math.max (returnvalue, leftmax+root.val); + } A if(Root.right! =NULL) { atRightmax =Maxpathsumhelper (root.right); -max = Math.max (max, Math.max (Rightmax, rightmax+root.val)); -returnvalue = Math.max (returnvalue, rightmax+root.val); - } - if(Root.left! =NULL&& Root.right! =NULL) { -max = Math.max (max, root.val+leftmax+Rightmax); in } - to returnreturnvalue; +}
LeetCode-124 Binary Tree Maximum Path Sum