124. Binary Tree Maximum Path Sum
使用全局变量记录结果
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 class Solution { 11 private int max = Integer.MIN_VALUE; 12 13 public int maxPathSum(TreeNode root) { 14 helper(root); 15 return max; 16 } 17 18 private int helper(TreeNode root) { 19 if (root == null) { 20 return 0; 21 } 22 int left = Math.max(helper(root.left), 0); 23 int right = Math.max(helper(root.right), 0); 24 25 max = Math.max(max, root.val + left + right); 26 27 return root.val + Math.max(left, right); 28 } 29 }