leetcode解题之124. Binary Tree Maximum Path Sum Java版 (二叉树的最大路径和)
来源:互联网 发布:网络公开课英语作文 编辑:程序博客网 时间:2024/06/07 10:35
124. Binary Tree Maximum Path Sum
Given a binary tree, find the maximum path sum.
For this problem, a path is defined as any sequence of nodes from some starting node to any node in the tree along the parent-child connections. The path must containat least one node and does not need to go through the root.
For example:
Given the below binary tree,
1 / \ 2 3
Return 6
.
计算二叉树中的路径之和最大值,起止节点为任意(此题和求二叉树的直径差不多,参考)
543. Diameter of Binary Tree Java版 (二叉树的最大直径)
private int maxVal = Integer.MIN_VALUE;public int maxPathSum(TreeNode root) {if (root == null)return 0;maxCore(root);return maxVal;}// 该函数返回是左右的最大路径和,而非左+右+root的最大值// 使用curValue,来标记左+右+rootprivate int maxCore(TreeNode root) {if (root == null)return 0;// 求以root为根的当前子树的最大路径和// 如果左右子树都是负数,// 那么就最大路径就是当前结点值(无论正负)int curValue = root.val;int lmax = maxCore(root.left);int rmax = maxCore(root.right);if (lmax > 0)curValue += lmax;if (rmax > 0)curValue += rmax;maxVal = Math.max(curValue, maxVal);// 返回以当前root为根的子树的最大路径和// 左右有可能都为负数,所以需要参与比较大小int thisMax = Math.max(root.val, Math.max(lmax + root.val, rmax + root.val));return thisMax;}
0 0
- leetcode解题之124. Binary Tree Maximum Path Sum Java版 (二叉树的最大路径和)
- LeetCode 124. Binary Tree Maximum Path Sum(二叉树最大路径和)
- LeetCode(Binary Tree Maximum Path Sum) 在二叉树中找出一条和最大的路径
- Binary Tree Maximum Path Sum 二叉树最大路径和
- Leetcode 124. Binary Tree Maximum Path Sum 最大路径和 解题报告
- Binary Tree Maximum Path Sum 二叉树最大路径和 @LeetCode
- Leetcode 124 Binary Tree Maximum Path Sum 二叉树最大路径和
- 【LeetCode】Binary Tree Maximum Path Sum二叉树中的最大路径和
- Binary Tree Maximum Path Sum (二叉树路径和的最大值) 【leetcode】
- 树的最大路径和 Binary Tree Maximum Path Sum
- 124. Binary Tree Maximum Path Sum 二叉树上的最大路径和
- Binary Tree Maximum Path Sum 二叉树中任意路径的最大和
- Binary Tree Maximum Path Sum 二叉树的最大路径和
- Binary Tree Maximum Path Sum 求二叉树的最大路径和
- 124 Binary Tree Maximum Path Sum 求二叉树的最大路径和
- 【二叉树】最大路径和【124. Binary Tree Maximum Path Sum】
- 94.Binary Tree Maximum Path Sum-二叉树中的最大路径和(中等题)
- LeetCode | Binary Tree Maximum Path Sum(二叉树的路径最大值)
- 如何给myeclipse下的tomacat配置新的jdk环境
- PPM与PCM的区别
- perl Selenium::Remote::Driver使用
- Mac安装Python版OpenCV
- 为什么说网站权重第一要素是网站结构
- leetcode解题之124. Binary Tree Maximum Path Sum Java版 (二叉树的最大路径和)
- error while loading shared libraries: xxx.so.x" 错误的原因和解决办法
- java 线程 通知 虚假唤醒
- HUST1027-Enemy Target!
- libpcap编程(1)
- dropDownSelect枚举下拉框
- PAT乙级(Basic Level)真题 >在霍格沃茨找零钱
- mutex与semaphore的区别
- 【Java8】Guava——Charsets