Binary Tree Maximum Path Sum

来源:互联网 发布:知乎还是百度知道 编辑:程序博客网 时间:2024/04/29 11:14

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.

/** * Definition for binary tree * public class TreeNode { *     int val; *     TreeNode left; *     TreeNode right; *     TreeNode(int x) { val = x; } * } */public class Solution {    int max;    public int maxPathSum(TreeNode root) {        // Start typing your Java solution below        // DO NOT write main() function       // max = (root==null)? 0: root.val;        if(root == null) {            return 0;        }        max = Integer.MIN_VALUE;        findMax(root);        return max;    }    public int findMax(TreeNode root){        if(root == null) {            return 0;        }        int left = Math.max(findMax(root.left),0);        int right = Math.max(findMax(root.right),0);        max = Math.max(root.val + left + right, max);        return root.val + Math.max(left,right);            }}


0 0
原创粉丝点击