124:二叉树中的最大路径和

This commit is contained in:
huangge1199 2021-05-28 11:20:17 +08:00
parent becdd62d1d
commit 752b24c5c5
3 changed files with 117 additions and 1 deletions

View File

@ -0,0 +1,84 @@
//路径 被定义为一条从树中任意节点出发沿父节点-子节点连接达到任意节点的序列同一个节点在一条路径序列中 至多出现一次 该路径 至少包含一个 节点且不
//一定经过根节点
//
// 路径和 是路径中各节点值的总和
//
// 给你一个二叉树的根节点 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
//
//
//
//
// 提示
//
//
// 树中节点数目范围是 [1, 3 * 104]
// -1000 <= Node.val <= 1000
//
// Related Topics 深度优先搜索 递归
// 👍 1057 👎 0
package leetcode.editor.cn;
import com.code.leet.entiy.TreeNode;
//124:二叉树中的最大路径和
public class BinaryTreeMaximumPathSum {
public static void main(String[] args) {
//测试代码
Solution solution = new BinaryTreeMaximumPathSum().new Solution();
}
//力扣代码
//leetcode submit region begin(Prohibit modification and deletion)
/**
* 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 max = Integer.MIN_VALUE;
public int maxPathSum(TreeNode root) {
dfs(root);
return max;
}
public int dfs(TreeNode root) {
if (root == null) {
return 0;
}
int left = Math.max(0, dfs(root.left));
int right = Math.max(0, dfs(root.right));
max = Math.max(left + right + root.val, max);
return Math.max(left, right) + root.val;
}
}
//leetcode submit region end(Prohibit modification and deletion)
}

View File

@ -0,0 +1,32 @@
<p><strong>路径</strong> 被定义为一条从树中任意节点出发,沿父节点-子节点连接,达到任意节点的序列。同一个节点在一条路径序列中 <strong>至多出现一次</strong> 。该路径<strong> 至少包含一个 </strong>节点,且不一定经过根节点。</p>
<p><strong>路径和</strong> 是路径中各节点值的总和。</p>
<p>给你一个二叉树的根节点 <code>root</code> ,返回其 <strong>最大路径和</strong></p>
<p> </p>
<p><strong>示例 1</strong></p>
<img alt="" src="https://assets.leetcode.com/uploads/2020/10/13/exx1.jpg" style="width: 322px; height: 182px;" />
<pre>
<strong>输入:</strong>root = [1,2,3]
<strong>输出:</strong>6
<strong>解释:</strong>最优路径是 2 -> 1 -> 3 ,路径和为 2 + 1 + 3 = 6</pre>
<p><strong>示例 2</strong></p>
<img alt="" src="https://assets.leetcode.com/uploads/2020/10/13/exx2.jpg" />
<pre>
<strong>输入:</strong>root = [-10,9,20,null,null,15,7]
<strong>输出:</strong>42
<strong>解释:</strong>最优路径是 15 -> 20 -> 7 ,路径和为 15 + 20 + 7 = 42
</pre>
<p> </p>
<p><strong>提示:</strong></p>
<ul>
<li>树中节点数目范围是 <code>[1, 3 * 10<sup>4</sup>]</code></li>
<li><code>-1000 <= Node.val <= 1000</code></li>
</ul>
<div><div>Related Topics</div><div><li></li><li>深度优先搜索</li><li>递归</li></div></div>\n<div><li>👍 1057</li><li>👎 0</li></div>

File diff suppressed because one or more lines are too long