一【题目类别】
- 深度优先搜索
二【题目难度】
- 困难
三【题目编号】
- 124.二叉树中的最大路径和
四【题目描述】
- 路径 被定义为一条从树中任意节点出发,沿父节点-子节点连接,达到任意节点的序列。同一个节点在一条路径序列中 至多出现一次 。该路径 至少包含一个 节点,且不一定经过根节点。
- 路径和 是路径中各节点值的总和。
- 给你一个二叉树的根节点 root ,返回其 最大路径和 。
五【题目示例】
-
示例 1:
- 输入:root = [1,2,3]
- 输出:6
- 解释:最优路径是 2 -> 1 -> 3 ,路径和为 2 + 1 + 3 = 6
-
示例 2:
- 输入:root = [-10,9,20,null,null,15,7]
- 输出:42
- 解释:最优路径是 15 -> 20 -> 7 ,路径和为 15 + 20 + 7 = 42
六【解题思路】
- 利用深度优先搜索和Floyd求最短路径的思想
- 为什么要使用Floyd求最短路径的思想呢?
- 读者们不如想一想Floyd求最短路径的过程:不停的更新中间节点以获得最小路径值,那么我们同样可以将这个思想利用到我们这道题目
- 我们可以将树当作图处理,每次都更新中间节点以获得最长路径值
- 那么具体做法就是:
- 首先遍历左子树,获取左子树的最长路径值
- 然后遍历右子树,获取右子树的最长路径值
- 然后更新结果,将左子树的最长路径值和右子树的最长路径值和当前节点值相加,看是否可以得到更长的路径值。总之,始终保持res为最大值
- 最后返回当前节点值和左右子树最长的路径长度和,这步为了可以返回最长的路径长度
- 递归结束之后,res中就保存了最长的路径长度,返回res即可
七【题目提示】
- 树中节点数目范围是 [ 1 , 3 ∗ 1 0 4 ] 树中节点数目范围是 [1, 3 * 10^4] 树中节点数目范围是[1,3∗104]
- − 1000 < = N o d e . v a l < = 1000 -1000 <= Node.val <= 1000 −1000<=Node.val<=1000
八【时间频度】
- 时间复杂度: O ( n ) O(n) O(n),其中 n n n 是二叉树的节点个数
- 空间复杂度: O ( n ) O(n) O(n),其中 n n n 是二叉树的节点个数
九【代码实现】
- Java语言版
package DFS;
public class p124_BinaryTreeMaximumPathSum {
int val;
p124_BinaryTreeMaximumPathSum left;
p124_BinaryTreeMaximumPathSum right;
public p124_BinaryTreeMaximumPathSum(int val) {
this.val = val;
}
public p124_BinaryTreeMaximumPathSum(int val, p124_BinaryTreeMaximumPathSum left, p124_BinaryTreeMaximumPathSum right) {
this.val = val;
this.left = left;
this.right = right;
}
public static void main(String[] args) {
p124_BinaryTreeMaximumPathSum root = new p124_BinaryTreeMaximumPathSum(1);
p124_BinaryTreeMaximumPathSum left = new p124_BinaryTreeMaximumPathSum(2);
p124_BinaryTreeMaximumPathSum right = new p124_BinaryTreeMaximumPathSum(3);
root.left = left;
root.right = right;
int res = maxPathSum(root);
System.out.println("res = " + res);
}
private static int res;
public static int maxPathSum(p124_BinaryTreeMaximumPathSum root) {
res = Integer.MIN_VALUE;
getRes(root);
return res;
}
private static int getRes(p124_BinaryTreeMaximumPathSum root) {
if (root == null) {
return 0;
}
int left = Math.max(0, getRes(root.left));
int right = Math.max(0, getRes(root.right));
res = Math.max(res, left + right + root.val);
return Math.max(left, right) + root.val;
}
}
- C语言版
#include<stdio.h>
#include<limits.h>
#include<math.h>
struct TreeNode {
int val;
struct TreeNode *left;
struct TreeNode *right;
};
int res;
int getRes(struct TreeNode* root)
{
if (root == NULL)
{
return 0;
}
int left = fmax(0, getRes(root->left));
int right = fmax(0, getRes(root->right));
res = fmax(res, left + right + root->val);
return fmax(left, right) + root->val;
}
int maxPathSum(struct TreeNode* root)
{
res = INT_MIN;
getRes(root);
return res;
}
/*主函数省略*/
十【提交结果】
-
Java语言版
-
C语言版