Binary Tree Maximum Path Sum 二叉树的最大路径和
来源:互联网 发布:小甲鱼python视频教程 编辑:程序博客网 时间:2024/05/16 05:28
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 does not need to go through the root.
For example:
Given the below binary tree,
1 / \ 2 3
Return 6
.
用递归实现这个代码非常简洁,易懂。
分析:现在的这个路径和,是一系列任意节点的和,只要这个路径上的相邻两个节点有parent-child连接就可以了。
我们要明白的一点是: 路径和一定是以某个节点node 为中间连接的路径。
又可以具体扩展:以节点node为中间连接的路径 = 当前的node.val + max(0, maxPath(node.left)) + max(0, maxPath(node.right))
加max是为了处理这类情况:
1 / \ -2 -3maxPath函数表示当前节点能够组成的最大 path sum,注意,不一定要到leaf node的。
运行时间:
代码:
private int maxSum = Integer.MIN_VALUE; public int maxPathSum(TreeNode root) { doMaxPathSum(root); return maxSum; } /** * * @param root * @return return the max path sum of root, */ private int doMaxPathSum(TreeNode root) { if (root == null) { return 0; } int left = doMaxPathSum(root.left); int right = doMaxPathSum(root.right); int curSum = root.val + Math.max(0, left) + Math.max(0, right); maxSum = Math.max(curSum, maxSum); // do not have to go to the leaf node. return Math.max(Math.max(left, right) + root.val, root.val); }
1 0
- Binary Tree Maximum Path Sum 二叉树最大路径和
- 树的最大路径和 Binary Tree Maximum Path Sum
- LeetCode(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 二叉树上的最大路径和
- Binary Tree Maximum Path Sum 二叉树最大路径和 @LeetCode
- Leetcode 124 Binary Tree Maximum Path Sum 二叉树最大路径和
- [LintCode] Binary Tree Maximum Path Sum (二叉树中的最大路径和)
- LeetCode 124. Binary Tree Maximum Path Sum(二叉树最大路径和)
- lintcode binary-tree-maximum-path-sum 二叉树中的最大路径和
- 94.Binary Tree Maximum Path Sum-二叉树中的最大路径和(中等题)
- 【二叉树】最大路径和【124. Binary Tree Maximum Path Sum】
- 【LeetCode】Binary Tree Maximum Path Sum二叉树中的最大路径和
- JavaShowAlgorithm-Binary Tree Maximum Path Sum 二叉树最大路径和
- 求二叉树最大路径和(Binary Tree Maximum Path Sum)
- 准备小圆点
- android进程重启及activity恢复
- Leetcode 347. Top K Frequent Elements
- objc_msgSend报错
- 用apt-get删除文件遇到了问题
- Binary Tree Maximum Path Sum 二叉树的最大路径和
- Andriod Studio科普篇——关于编译的常见问题
- JavaWeb学习之Servlet3.0新特性详解
- Java多线程之内存可见性
- 测试用例编写标准
- Activity的概念介绍
- Android拨打电话
- Android Studio使用gradle-retrolambda支持Java8 新特性 Lambde表达式
- c#面试题