[Leetcode] Binary Tree Maximum Path Sum (Java)

来源:互联网 发布:日本的偶像文化 知乎 编辑:程序博客网 时间:2024/05/23 20:08

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.

找最大路径和,跟找最长叶子节点距离一样的思路,2种可能:

1)包含root

2)不包含root

用maxLen保存当前最大和,并每次计算包含root的,并更新maxLen:

public class Solution {    private int maxLen = Integer.MIN_VALUE;    public int maxPathSum(TreeNode root) {maxPath(root);return maxLen;}private int maxPath(TreeNode root){if(root==null)return 0;int left = maxPath(root.left);int right = maxPath(root.right);int local = root.val;if(left>0)local+=left;if(right>0)local+=right;maxLen=Math.max(maxLen, local);return Math.max(root.val, root.val+Math.max(left,right));}}


0 0