標籤:leetcode java binary tree maximum
題目:
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.
題意:
給定一棵二叉樹,找出最大得路徑和。
路徑的起始和結束位置可以是樹中的任意節點。
比如,
給定如下的一棵二叉樹
1 / 2 3
返回
6.
演算法分析:
1) Recursively solve this problem
2) Get largest left sum and right sum
3) Compare to the stored maximum
* 這裡有一個地方要想明白,最短路徑結果有四種可能,當前加左,當前加右,當前自己,當前加左、右子樹的return值
* 而return值,有三種可能,當前加左,當前加右,當前自己。
* 這裡return裡不是當前加左右子樹,也就是不能把left和right加起來了...因為只是一條路..,故不符合題目要求。
* 在這裡,函數的返回值定義為以自己為根的一條從根到子結點的最長路徑
AC代碼:
<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>
著作權聲明:本文為博主原創文章,轉載註明出處
[LeetCode][Java] Binary Tree Maximum Path Sum