> For the complete documentation index, see [llms.txt](https://junnie.gitbook.io/nine-chapter/llms.txt). Markdown versions of documentation pages are available by appending `.md` to page URLs; this page is available as [Markdown](https://junnie.gitbook.io/nine-chapter/2.binary-tree/475.binary-tree-maximum-path-sum-ii.md).

# 475.Binary Tree Maximum Path Sum II

## 1.Description(Medium)

Given a binary tree, find the maximum path sum from root.

The path may end at any node in the tree and contain at least one node in it.

**Example**

Given the below binary tree:

```
  1
 / \
2   3
```

return`4`. (1->3)

## 2.Code

判断left 和right的正负，全负就只返回root.val,一方负就返回另一方+root.val，全正就取max(left,right)+root.val

```
public int maxPathSum2(TreeNode root) {
        if(root==null){
         return Integer.MIN_VALUE;
     }
     int left=maxPathSum2(root.left);
     int right=maxPathSum2(root.right);

     if(left<0 && right<0){
         return root.val;
     }
     if(left<0){
         return right+root.val;
     }
     if(right<0){
         return left+root.val;
     }
     return Math.max(left,right)+root.val;
}
```
