LeetCode 124. 二叉树中的最大路径和
题目描述
路径 被定义为一条从树中任意节点出发,沿父节点-子节点连接,达到任意节点的序列。同一个节点在一条路径序列中 至多出现一次 。该路径 至少包含一个 节点,且不一定经过根节点。路径和 是路径中各节点值的总和。
给你一个二叉树的根节点 root ,返回其 最大路径和 。
示例 1:
输入:root = [1,2,3]
输出:6
解释:最优路径是 2 -> 1 -> 3 ,路径和为 2 + 1 + 3 = 6
LeetCode 124. 二叉树中的最大路径和
提示:
树中节点数目范围是 [1, 3 * 104]
-1000 <= Node.val <= 1000
一、解题关键词
二、解题报告
1.思路分析
树,一定要递归
2.时间复杂度
3.代码示例
/**
* Definition for a binary tree node.
* public 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;
* }
* }
*/
class Solution {
int maxSum = Integer.MIN_VALUE;
public int maxPathSum(TreeNode root) {
//左右子树最大和 需要动态规划
//1、递归 2、深度优先
maxGain(root);
return maxSum;
}
int maxGain(TreeNode root){
if(null == root){
return 0;
}
int leftValue = Math.max(maxGain(root.left),0);
int rightVAlue = Math.max(maxGain(root.right),0);
int priceNewPath = root.val + leftValue + rightVAlue;
//更新答案
maxSum = Math.max(maxSum,priceNewPath);
return root.val + Math.max(leftValue,rightVAlue);
}
}
2.知识点
树的遍历