标签:
题目描述:/** * Definition for a binary tree node. * public class TreeNode { * public int val; * public TreeNode left; * public TreeNode right; * public TreeNode(int x) { val = x; } * } */ public class Solution { public int MaxPathSum(TreeNode root) { var max = int.MinValue; CountMax(root, ref max); return max; } private int? CountMax(TreeNode root, ref int max) { if(root == null){ return null; } var leftMax = CountMax(root.left, ref max); var rightMax = CountMax(root.right, ref max); var maxRoute = root.val; max = Math.Max(maxRoute, max); if(leftMax.HasValue){ maxRoute = Math.Max(maxRoute, root.val + leftMax.Value);// Max(current , left) max = Math.Max(Math.Max(max, leftMax.Value), maxRoute);// Max(left, current , left + current) } if(rightMax.HasValue){ maxRoute = Math.Max(maxRoute, root.val + rightMax.Value);// Max(currnet, left, right) max = Math.Max(Math.Max(max, rightMax.Value), maxRoute);// Max(left, right, current , right + current) } if(leftMax.HasValue && rightMax.HasValue){ max = Math.Max(root.val + leftMax.Value + rightMax.Value, max);//Max(left ,right, current , right + current, left+right +current) } return maxRoute; } }
LeetCode-- Binary Tree Maximum Path Sum
标签:
原文地址:http://blog.csdn.net/lan_liang/article/details/50144507