https://leetcode.cn/problems/binary-tree-maximum-path-sum/description/?envType=study-plan-v2&envId=top-interview-150
对于这题我开始的思路是路径我们可以看作是一条线,我们确定一个点后可以往两侧延伸(就是左右子树的方向),我们通过递归找到以该节点出发的左右两侧的最大路径拼接后就是经过该节点的最大路径和,我们最后只要将所有节点当作出发点遍历一次就可以找到最大路径。
所以我们的工作就两步:1.写一个可以以一个节点出发找到最大路径的函数 2.遍历所有节点
class Solution {
public static class TreeNode {
int val;
TreeNode left;
TreeNode right;
TreeNode() {}
TreeNode(int val) { this.val = val; }
TreeNode(int val, TreeNode left, TreeNode right) {
this.val = val;
this.left = left;
this.right = right;
}
}
public static void main(String[] args) {
//-1001代表null
int[] arr = {-1,5,-1001,4,-1001,-1001,2,-4, -1001};
TreeNode root = new TreeNode(arr[0]);
Queue<TreeNode> nodes = new LinkedList<>();
nodes.add(root);
for(int i = 1; i < arr.length; i += 2) {
TreeNode top = nodes.poll();
TreeNode l = null;
TreeNode r = null;
if(arr[i] != -1001) l = new TreeNode(arr[i]);
if(arr[i + 1] != -1001) r = new TreeNode(arr[i + 1]);
top.left = l;
top.right = r;
if(l != null) nodes.add(l);
if(r != null) nodes.add(r);
}
System.out.println(new Solution().maxPathSum(root));
}
public int maxPathSum(TreeNode root) {
if(root == null) return 0;
if(root.left == null && root.right == null) return root.val;
Queue<TreeNode> nodes = new LinkedList<>();
nodes.add(root);
int leftSum = 0, rightSum = 0, max = Integer.MIN_VALUE;
//遍历所有节点
while(!nodes.isEmpty()) {
TreeNode top = nodes.poll();
if(top.left != null) {
nodes.add(top.left);
leftSum = def(top.left, 0);
}
if(top.right != null) {
nodes.add(top.right);
rightSum = def(top.right, 0);
}
max = Math.max(max, (Math.max(leftSum, 0)) + (Math.max(rightSum, 0)) + top.val);
leftSum = 0;
rightSum = 0;
}
return max;
}
public int def(TreeNode root, int sum) {
sum += root.val;
if(root.left == null && root.right == null) return sum;
/*
* (root.left == null ? 0 : def(root.left, sum)) 表示如果左子树为空,则返回0,否则返回以左子树为根节点的最大路径和
* Math.max((root.left == null ? 0 : def(root.left, sum)), sum) 表示以左子树为根节点的最大路径和与当前路径和值取最大值,因为我们不一定要加上新的节点(因为可能加上后反而变小)
* 右子树的逻辑和左子树相同
* */
return Math.max(Math.max((root.left == null ? 0 : def(root.left, sum)), sum), Math.max((root.right == null ? 0 : def(root.right, sum)), sum));
}
}