Topic:
Given a binary tree, find the maximum path sum.
The path may start and end at any node in the tree.
Example
Given the below binary tree:
1 / 2 3
Return 6
.
Ideas:
The longest path in the calculation tree is 2 cases:
1. Path through the root.
(1) If the path of Zuozi from Zoshigen to any node is greater than 0, it can be chained to root
(2) If the right subtree from the right tree root to any one of the node's path is greater than 0, you can link to root
2. Path not through the root. This can take the maximum value of the path of the Zuozi and right sub-tree.
So create a inner class:
Record 2 values:
1. Maximum path of this tree.
2. The tree starts from the root node to the maximum path of any one node.
Note that when root = = NULL, the above 2 values are set to Integer_min_value; Because no node is desirable, there is no solution. So as not to interfere with the calculation of recursion
Because there is the appearance of Integer.min_value, so in addition to consider the cross-border situation, make judgments.
PS: has been used in C + + brush, suddenly decided to change Java, found ... or Java simple ...
/*** Definition of TreeNode: * public class TreeNode {* public int val; * Public TreeNode left, right; * PU Blic TreeNode (int val) {* This.val = val; * This.left = This.right = null; *} *}*/ Public classSolution {/** * @paramroot:the root of binary tree. * @return: An integer. */ Public classreturntype{intMaxPath; intSinglepath; ReturnType (intMaxintSingle ) { This. MaxPath =Max; This. Singlepath =Single ; } } PublicReturnType MaxPath (TreeNode root) {returntype res=Newreturntype (Integer.min_value, Integer.min_value); if(Root = =NULL) { returnRes; } //DivideReturnType left =MaxPath (Root.left); ReturnType Right=MaxPath (root.right); //Conquer//Direct addition may be out of bounds, Singlepath is less than 0 current Singlepath = Root.val intIncreaseleft = Math.max (left.singlepath, 0); intIncreaseright = Math.max (right.singlepath, 0); Res.singlepath= Math.max (Increaseleft + root.val, Increaseright +root.val); //Direct addition may be out of boundsRes.maxpath =Math.max (Right.maxpath, Left.maxpath); Res.maxpath= Math.max (Res.maxpath, increaseleft + increaseright +root.val); returnRes; } Public intmaxpathsum (TreeNode root) {//Write your code here returnMaxPath (Root). MaxPath; }}
Ref:http://www.cnblogs.com/yuzhangcmu/p/4172855.html
[Problem Solving report] Binary Tree Maximum Path Sum