码迷,mamicode.com
首页 > 其他好文 > 详细

[Leetcode] Binary Tree Maximum Path Sum

时间:2014-11-30 16:42:57      阅读:200      评论:0      收藏:0      [点我收藏+]

标签:style   blog   io   ar   color   sp   for   on   div   

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

标签:style   blog   io   ar   color   sp   for   on   div   

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

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!