執行結果:
通過
顯示詳情
執行用時 :1 ms, 在所有 Java 提交中擊敗了99.80% 的用戶
內存消耗 :41.5 MB, 在所有 Java 提交中擊敗了15.00%的用戶
題目:
給定一個非空二叉樹,返回其最大路徑和。
本題中,路徑被定義爲一條從樹中任意節點出發,達到任意節點的序列。該路徑至少包含一個節點,且不一定經過根節點。
示例 1:
輸入: [1,2,3]
1
/ \
2 3
輸出: 6
示例 2:
輸入: [-10,9,20,null,null,15,7]
-10
/ \
9 20
/ \
15 7
輸出: 42
來源:力扣(LeetCode)
鏈接:https://leetcode-cn.com/problems/binary-tree-maximum-path-sum
著作權歸領釦網絡所有。商業轉載請聯繫官方授權,非商業轉載請註明出處。
思路:
深度遍歷,具體見代碼。
代碼:
/**
* Definition for a binary tree node.
* public class TreeNode {
* int val;
* TreeNode left;
* TreeNode right;
* TreeNode(int x) { val = x; }
* }
*/
class Solution {
int max=Integer.MIN_VALUE;
public int maxPathSum(TreeNode root) {
if(root==null)
{
return 0;
}
dfs(root);
return max;
}
public int dfs(TreeNode root)
{
if(root==null)
{
return 0;
}
//左邊如果爲負還不如沒有
int leftMax=Math.max(0,dfs(root.left));
//右邊如果爲負還不如沒有
int rightMax=Math.max(0,dfs(root.right));
//不斷更新最大值
max=Math.max(max,root.val+leftMax+rightMax);
//如果往上返回的話,左右只能一條路
return root.val+Math.max(leftMax,rightMax);
}
}