1. 程式人生 > >題目:二叉樹中的最大路徑和

題目:二叉樹中的最大路徑和

/**
* 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.
     */
    public int ret = Integer.MIN_VALUE;
    public int maxPathSum(TreeNode root) {
        // write your code here
         if(null==root) return 0;
         rootPath(root);
         return ret;
    }
     public int rootPath(TreeNode root){
         if(null==root) return 0;
         int sum = root.val;
          int left = rootPath(root.left);
          int right = rootPath(root.right);
          if(left>0){
               sum += left;
          }
          if(right>0){
               sum += right;
          }
          if(sum>ret){
               ret = sum;
          }
          return Math.max(root.val, Math.max(left+root.val, right+root.val));                 
    }
}