LeetCode 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.

For example:
Given the below binary tree,

       1
      / \
     2   3


Return6.


解题思路:

记录一个全局的值为max,然后判断左子树单边最大值 记为left 和右子树单边最大值 right,max = Math.max(left, 0)+ Math.max(right, 0) + root.val,  返回  Math.max(left, right) + root.val

public class Solution {
   int maxVal = Integer.MIN_VALUE;
	public int maxPathSum(TreeNode root) {
		down(root);
		return maxVal;
	}
	
	public int down(TreeNode root) {
		if (root == null) {
			return 0;
		}
		int left = Math.max(down(root.left), 0);
		int right = Math.max(down(root.right), 0);
		maxVal = Math.max(maxVal, left + right + root.val); //记录左边 + 右边 + 自己的和 与 最大值比较
		return Math.max(left, right) + root.val;  //返回一边的最大值
	}
}



你可能感兴趣的:(LeetCode binary-tree-maximum-path-sum)