Binary Tree Maximum Path Sum Java 递归解法

来源:互联网 发布:海王星写频软件 编辑:程序博客网 时间:2024/05/12 05:54

原题:

 Binary Tree Maximum Path Sum

Given a binary tree, find the maximum path sum.

The path may start and end at any node in the tree.

Example

Given the below binary tree:

  1 / \2   3

return 6.

link:http://www.lintcode.com/en/problem/binary-tree-maximum-path-sum/

花了一个早上的时间就做出来这一道题。不知道是该开心还是该难过 :(

我一开始最为担心的是我的解法如何保证我找到的path的连通性。后来决定用递归的方式解决。

二叉树天生自带Divide&Conquer属性 感觉所有二叉树的问题可以一招鲜吃遍天。

我的思路就是Divide到左右子树然后,分别求出左右字数的Max Path

其实这道题一共只会有三种情况。

1.最大路径在根节点的左子树。
2.最大路径在根节点的右子树。
3.最大路径经过根节点并且分布在左右子树。

这三种情况一定互斥。

Talk is cheap,show you the code
/** * Definition of TreeNode: * public class TreeNode { *     public int val; *     public TreeNode left, right; *     public TreeNode(int val) { *         this.val = val; *         this.left = this.right = null; *     } * } */public class Solution {    /**     * @param root: The root of binary tree.     * @return: An integer.     */            class Result {            int maxOneWay;            int maxValue;            Result(int maxOneWay,int maxValue){                this.maxOneWay = maxOneWay;                this.maxValue = maxValue;            }        }            private Result maxSum(TreeNode root){                if(root == null){            Result r = new Result(0,Integer.MIN_VALUE);            return r;        }                //Divide        Result left = maxSum ( root.left );        Result right = maxSum ( root.right );        //Conquer        int maxOneWay = Math.max((Math.max(left.maxOneWay , right.maxOneWay)+root.val),0);        int maxValue = Math.max(Math.max( left.maxValue , right.maxValue) , left.maxOneWay+right.maxOneWay+root.val);                       Result r = new Result(maxOneWay , maxValue);        return r;                    }                         public int maxPathSum(TreeNode root){        // write your code here        //1. the Maximum is on the left child tree        //2. the Maximum is on the right child tree        //3. the Maximum the left part + right part + root value        Result r = maxSum(root);        return r.maxValue;                              }}




0 0