首页 > 其他 > 详细

[Leetcode] Binary Tree Maximum Path Sum

时间:2014-11-30 16:42:31      阅读:240      评论: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   3

 

Return 6.

 

Solution:

 1 /**
 2  * Definition for binary tree
 3  * public class TreeNode {
 4  *     int val;
 5  *     TreeNode left;
 6  *     TreeNode right;
 7  *     TreeNode(int x) { val = x; }
 8  * }
 9  */
10 public class Solution {
11     int result;
12     public int maxPathSum(TreeNode root) {
13         result=Integer.MIN_VALUE;
14         dfs(root);
15         return result;
16     }
17     private int dfs(TreeNode root) {
18         // TODO Auto-generated method stub
19         if(root==null)
20             return 0;
21         int l=0;
22         int r=0;
23         if(root.left!=null)
24             l=dfs(root.left);
25         if(root.right!=null)
26             r=dfs(root.right);
27         int sum=root.val;
28         if(l>0)
29             sum+=l;
30         if(r>0)
31             sum+=r;
32         result=Math.max(result,sum);
33         return Math.max(0,Math.max(l,r))+root.val; //只能选择左边儿的或者右边儿的来组成一个path
34     }
35 }

 

[Leetcode] Binary Tree Maximum Path Sum

原文:http://www.cnblogs.com/Phoebe815/p/4133297.html

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