Created
February 10, 2018 10:24
-
-
Save ChrisLinn/2c48b6dd5ae4e04c50e4d770d9280b9d to your computer and use it in GitHub Desktop.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| //Leetcode 124. Binary Tree Maximum Path Sum | |
| //crab's code. I can never understand, but it works at the end? | |
| //why?why?why??? | |
| /** | |
| * Definition for binary tree | |
| * public class TreeNode { | |
| * int val; | |
| * TreeNode left; | |
| * TreeNode right; | |
| * TreeNode(int x) { val = x; } | |
| * } | |
| */ | |
| import java.lang.Math; | |
| public class Solution { | |
| public int maxPathSum(TreeNode root) { | |
| int maxSum = 0; | |
| if(root != null){ | |
| int[] result = getMaxSum(root); | |
| maxSum = Math.max(result[0],result[1]); | |
| } | |
| return maxSum; | |
| } | |
| public int[] getMaxSum(TreeNode node) | |
| { | |
| int lMax = -999999, lWMax = -99999,rMax = -99999,rWMax = -99999; | |
| int[] result = new int[2]; | |
| if(node.left == null && node.right == null) | |
| { | |
| //??? | |
| result[0] = node.val; | |
| result [1] = node.val; | |
| return result; | |
| } | |
| else | |
| { | |
| int[] temp; | |
| if(node.left!=null){ | |
| temp = getMaxSum(node.left); | |
| lMax = temp[0]; | |
| lWMax = temp[1]; | |
| } | |
| if(node.right != null) | |
| { | |
| temp = getMaxSum(node.right); | |
| rMax = temp[0]; | |
| rWMax = temp[1]; | |
| } | |
| int t1 = Math.max(lWMax,rWMax); | |
| int t2 = Math.max(lMax,rMax); | |
| result[0] = Math.max(t1,Math.max(t2,lWMax+rWMax+node.val)); | |
| result[1] = Math.max(node.val,t1+node.val); | |
| return result; | |
| } | |
| } | |
| } |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment