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 .
Problem Solving Ideas:
DFS brute force enumeration, note that if the static global variable is used, it can be passed inside the IDE, but cannot be tested on OJ, so you need to create a class to store the results, and the Java implementation is as follows:
public class Solution {static public int maxpathsum (TreeNode root) {result result=new result (Integer.min_value);d FS (root , result); return result.val;} static int Dfs (TreeNode root,result Result) {if (root = null) return 0;int left_sum = Math.max (0, DFS (root.left,result)); I NT Right_sum = Math.max (0, DFS (root.right,result)); result.val = Math.max (result.val, left_sum + right_sum + root.val); ret Urn Math.max (left_sum, right_sum) + Root.val;}} Class Result{int Val; Result () {this.val=integer.min_value;} Result (int val) {this.val=val;}}
Java for Leetcode 124 Binary Tree Maximum Path Sum