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 3Return 6.
Difficulty: 75.
According to the ideas of others, this question is the path and question of the tree. However, what is different from the ordinary one is that the path here can not only go from the root to a node, in addition, the path can be a node in the left subtree, and then reach the node in the right subtree, just as it can start and end at any node in the question. The return value of a function is defined as the longest path from the root node to the leaf node. the return value is used to provide its parent node with the longest path for computing. In this way, the longest path of a node is its left subtree return value (if it is greater than 0), plus the return value of the right subtree (if it is greater than 0 ), add your own value. When the longest path is obtained in the process, check whether it is the longest path. If it is the longest path, update it. The essence of an algorithm is a tree traversal, so the complexity is O (n ). The space is still the size of the stack O (logn ). Note that the path storage method is a problem. If an integer variable is used to replace the recursion, the function cannot change the real parameter, therefore, the first element of the arraylist <integer> res object is used to store the largest PATH value.
1 /** 2 * Definition for binary tree 3 * public class TreeNode { 4 * int val; 5 * TreeNode left; 6 * TreeNode right; 7 * TreeNode(int x) { val = x; } 8 * } 9 */10 public class Solution {11 public int maxPathSum(TreeNode root) {12 if (root == null) return 0;13 ArrayList<Integer> res = new ArrayList<Integer>();14 res.add(Integer.MIN_VALUE);15 FindMaxSum(root, res);16 return res.get(0);17 }18 19 public int FindMaxSum(TreeNode root, ArrayList<Integer> res) {20 if (root == null) {21 return 0;22 }23 int leftsum = FindMaxSum(root.left, res);24 int rightsum = FindMaxSum(root.right, res);25 int maxsum = root.val + (leftsum>0? leftsum : 0) + (rightsum>0? rightsum : 0);26 if (maxsum > res.get(0)) res.set(0, maxsum);27 return root.val + Math.max(leftsum, Math.max(rightsum, 0));28 }29 }
Leetcode: Binary Tree maximum path sum