LeetCode(力扣)6月「每日 1 题」

 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 }
View Code

猜你喜欢

转载自www.cnblogs.com/tongan-java/p/13173462.html