首页 > 其他 > 详细

leetcode--Binary Tree Maximum Path Sum

时间:2014-02-26 21:17:45      阅读:527      评论: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.

 

Have you been asked this question in an interview? 

 

The problem can solved using the DFS

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
/**
 * Definition for binary tree
 * public class TreeNode {
 *     int val;
 *     TreeNode left;
 *     TreeNode right;
 *     TreeNode(int x) { val = x; }
 * }
 */
public class Solution {
    public int maxPathSum(TreeNode root) {
       int maxSum = Integer.MIN_VALUE; 
        if(root != null){
            Stack<TreeNode> sta = new Stack<TreeNode>();
            HashSet<TreeNode> hset = new HashSet<TreeNode>();
            sta.push(root);
            hset.add(root);
            while(!sta.empty()){
                TreeNode aNode = sta.pop();
                if(aNode.left != null && hset.add(aNode.left)){
                    sta.push(aNode);
                    sta.push(aNode.left);
                }
                else if(aNode.right != null && hset.add(aNode.right)){
                    sta.push(aNode);
                    sta.push(aNode.right);
                }
                else{
                    int leftMax = (aNode.left == null) ? 0 : aNode.left.val;
                    int rightMax = (aNode.right == null) ? 0 : aNode.right.val;
                    int sum = aNode.val + leftMax + rightMax;
                    aNode.val = Math.max(aNode.val, Math.max(leftMax + aNode.val, rightMax + aNode.val));
                    maxSum = Math.max(maxSum, Math.max(aNode.val, sum));                   
                }                          
            }      
        }
        return maxSum;
    }
}

  

 

leetcode--Binary Tree Maximum Path Sum,布布扣,bubuko.com

leetcode--Binary Tree Maximum Path Sum

原文:http://www.cnblogs.com/averillzheng/p/3568343.html

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