Given a binary tree, find the maximum path sum.
For this problem, a path is defined as any sequence of nodes from some starting node to any node in the tree along the parent-child connections. The path must contain at least one node and does not need to go through the root.
For example:
Given the below binary tree,
1 / \ 2 3
Return 6
.
1 /** 2 * Definition for a binary tree node. 3 * public class TreeNode { 4 * public int val; 5 * public TreeNode left; 6 * public TreeNode right; 7 * public TreeNode(int x) { val = x; } 8 * } 9 */ 10 public class Solution { 11 public int MaxPathSum(TreeNode root) { 12 var max = new int[1] {Int32.MinValue}; 13 DFS(root, max); 14 return max[0]; 15 } 16 17 private int DFS(TreeNode node, int[] max) 18 { 19 if (node == null) return Int32.MinValue; 20 21 max[0] = Math.Max(max[0], node.val); 22 23 var left = DFS(node.left, max); 24 var right = DFS(node.right, max); 25 26 if (left >= 0 && right >= 0) 27 { 28 max[0] = Math.Max(max[0], left + right + node.val); 29 return left >= right ? left + node.val : right + node.val; 30 } 31 else if (left >= 0) 32 { 33 max[0] = Math.Max(max[0], left + node.val); 34 return left + node.val; 35 } 36 else if (right >= 0) 37 { 38 max[0] = Math.Max(max[0], right + node.val); 39 return right + node.val; 40 } 41 42 return node.val; 43 } 44 }