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
.
Solution:
1 /**2 * Definition for binary tree3 * public class TreeNode {4 * int val;5 * TreeNode left;6 * TreeNode right;7 * TreeNode (int x) {val = x;}8 * }9 */Ten Public classSolution { One intresult; A Public intmaxpathsum (TreeNode root) { -result=Integer.min_value; - Dfs (root); the returnresult; - } - Private intdfs (TreeNode root) { - //TODO auto-generated Method Stub + if(root==NULL) - return0; + intL=0; A intR=0; at if(root.left!=NULL) -L=DFS (root.left); - if(root.right!=NULL) -R=DFS (root.right); - intsum=Root.val; - if(l>0) insum+=l; - if(r>0) tosum+=R; +result=Math.max (result,sum); - returnMath.max (0,math.max (l,r)) +root.val;//can only choose the left side or the right side to form a path the } *}
[Leetcode] Binary Tree Maximum Path Sum