Title:
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
.
Test Instructions:
Given a binary tree, find the maximum path and.
The starting and ending positions of a path can be any node in the tree.
Like what
Given a binary tree as follows
1 / 2 3
return
6
.
Algorithm Analysis:
1) recursively solve this problem
2) Get largest left sum and right sum
3) Compare to the stored maximum
* Here's a place to figure out, the shortest path result has four possible, current plus left, current plus right, current self, current plus left and right subtree return value
* and return value, there are three possible, current plus left, current plus right, the current self.
* Here return is not the current subtree, that is, the left and right add up ... Because it is only a road, it does not meet the requirements of the topic.
* Here, the return value of the function is defined as the longest path from the root to the child node with its own root
AC Code:
<span style= "Font-family:microsoft yahei;font-size:12px;" >/** * Definition for a binary tree node. * public class TreeNode {* int val, * TreeNode left, * TreeNode right; * TreeNode (int x) {val = x;} *} */public class Solution {public int maxpathsum (TreeNode root) { int max[] = new int[1]; Max[0] = Integer.min_value; Calculatesum (Root, max); return max[0]; } public int calculatesum (TreeNode root, int[] max) { if (root = null) return 0; int left = Calculatesum (Root.left, max); int right = Calculatesum (Root.right, max); int current = Math.max (Root.val, Math.max (Root.val + left, Root.val + right)); Max[0] = Math.max (max[0], Math.max (current, left + Root.val + right)); return current; }} </span>
Copyright NOTICE: This article is the original article of Bo Master, reprint annotated source
[Leetcode] [Java] Binary Tree Maximum Path Sum