二叉樹的最長路徑和(Binary Tree Maximum Path Sum)
阿新 • • 發佈:2019-01-04
題目:
Given a binary tree, find the maximum path sum. For this problem, a path is defined as any sequence of nodes from some starting node to any node in the tree along the parent-child connections. The path must contain at least one node and does not need to go through the root
google 翻譯:
給定一個二叉樹,找到最大路徑和。 對於這個問題,路徑被定義為從父子連線到某個起始節點到樹中任何節點的任何節點序列。 該路徑必須包含至少一個節點,不需要遍歷根。
示例:
就是從任意節點開始到任意節點結束所走過的最大距離
思路:
最大值的可能情況,雖然題目說不需要遍歷根節點,其實是需要根節點的。
把根節點理解成父節點更好一些,因為需要父節點和別的連成一條線。
最大值來自
- root+左邊的某條路徑+右邊的某條路徑
- 左邊的某條路徑 + root
- root + 右邊的某條路徑
- root
練習傳送門:這裡
java實現:
/**
* 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) {
record(root);
return max;
}
public int record(TreeNode root){
if(root==null) return 0;
int l=Math.max(0,record(root.left));
int r=Math.max(0,record(root.right));
max=Math.max(max,root.val+l+r);
return root.val+Math.max(l,r);
}
}