给定一个非空二叉树,返回其最大路径和。
本题中,路径被定义为一条从树中任意节点出发,达到任意节点的序列。该路径至少包含一个节点,且不一定经过根节点。
示例 1:
输入: [1,2,3]
1
/ \
2 3
输出: 6
示例 2:
输入: [-10,9,20,null,null,15,7]
-10
/ \
9 20
/ \
15 7
输出: 42
1 /** 2 * Definition for a binary tree node. 3 * public class TreeNode { 4 * int val; 5 * TreeNode left; 6 * TreeNode right; 7 * TreeNode(int x) { val = x; } 8 * } 9 */ 10 /* 11 采用递归方式,每个递归方法中得到左右结点的最大路径(因为要求最大路径,所以若所得的左右结点的最大路径为负数,则让他们等于0),并返回自身结点的最大路径(因为返回值是提供给父结点使用,所以此时返回的只包含自身结点加上左右结点中最大的一个),在每次递归中,判断自身结点加上左右结点的和是否为最大路径(因为可能在自身结点拐角,不经过其父结点) 12 */ 13 class Solution { 14 private int max=Integer.MIN_VALUE; 15 public int maxPathSum(TreeNode root) { 16 Deal(root); 17 return max; 18 19 } 20 public int Deal(TreeNode root) { 21 if(root==null) 22 return 0; 23 int left = Math.max(0, Deal(root.left)); 24 int right = Math.max(0, Deal(root.right)); 25 int sum; 26 int result; 27 28 sum=Math.max(left,right)+root.val; 29 result=root.val+right+left; 30 max=Math.max(max,result); 31 return sum; 32 } 33 }