首页 > 其他 > 详细

Binary Tree Maximum Path Sum

时间:2019-02-23 15:32:37      阅读:143      评论:0      收藏:0      [点我收藏+]

题目:

Given a binary tree, find the maximum path sum.
The path may start and end at any node in the tree.
For example, given the below binary tree,
1
/ \
2 4
/ \
2 3
The highlighted path yields the maximum sum 10

 

解答:

 1 public class Solution {
 2     private int maxSum;
 3 
 4     public int getPathSum(TreeNode root) {
 5         maxSum = Integer.MIN_VALUE;
 6         findMax(root);
 7         return maxSum;
 8     }
 9 
10     private int findMax(TreeNode p) {
11         if(p == null) {
12             return 0;
13         }
14 
15         int left = findMax(p.left);
16         int right = findMax(p.right);
17 
18         maxSum = Math.max(p.val + left + right, maxSum);
19         int ret = p.val + Math.max(left, right);
20         return ret > 0? ret:0;
21     }
22 
23 
24 }

 

Binary Tree Maximum Path Sum

原文:https://www.cnblogs.com/wylwyl/p/10422709.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!