問題鏈接:https://www.nowcoder.com/questionTerminal/da785ea0f64b442488c125b441a4ba4a
問題
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
Return6.
求二叉樹的最大路徑和。路徑的起點和終點可以是任意節點。
分析
二叉樹裏的任何路徑都是二叉樹,都有根節點。所以問題等價如下:
通過根節點的最大路徑和,而二叉樹的每個節點都可以是根節點,所以分別求出以每個節點爲根節點的二叉樹中通過根節點的最大路徑和,並比較出最大的即可。
代碼
class TreeNode {
int val;
TreeNode left;
TreeNode right;
TreeNode(int x) {
val = x;
}
}
import java.util.ArrayList;
public class Solution {
public int maxPathSum(TreeNode root) {
if (root == null) {
return 0;
}
// 通過每個根節點的路徑和數組
ArrayList<Integer> paths = new ArrayList<>();
rootMaxPath(root, paths);
int max = paths.get(0);
int size = paths.size();
for (int i = 1; i < size; i++) {
if (paths.get(i) > max) {
max = paths.get(i);
}
}
return max;
}
/**
* 求二叉樹最大的半邊路徑和(包含根節點)
*
* @param root
* 根節點
* @param paths
* 通過每個根節點的路徑和數組
* @return
*/
private int rootMaxPath(TreeNode root, ArrayList<Integer> paths) {
if (null == root) {
return 0;
}
int path = root.val;
int lmax = rootMaxPath(root.left, paths);
int rmax = rootMaxPath(root.right, paths);
if (lmax > 0) {
path += lmax;
}
if (rmax > 0) {
path += rmax;
}
paths.add(path);
int max = Math.max(lmax, rmax);
return root.val + Math.max(max, 0);
}
}