LeetCode Binary Tree Maximum Path Sum
来源:互联网 发布:dnf网络不稳定 编辑:程序博客网 时间:2024/04/29 22:03
LeetCode解题之Binary Tree Maximum Path Sum
原题
求一棵二叉树中最大的路径和。该路径可以是二叉树中某一节点到树中任意一个节点的所经过的路径,不允许重复经过一个节点,不必经过根节点。
注意点:
- 无
例子:
输入:
1 / \ 2 3
输出: 6
解题思路
采用递归的方法,我们知道一条路径必定有一个节点最接近根节点,而该条路径的和就是这个节点的值加上它左右路径的和。我们现在要求最大路径和,那么就要分别得到左右两条路径的最大和。而左路径的最大和为左节点的值加上它左右路径中较大的路径和,右路径最大和为右节点的值加上它左右路径中较大的路径和。注意如果某条子路径的和为负,应该将该条子路径直接砍掉。
AC源码
# Definition for a binary tree node.class TreeNode(object): def __init__(self, x): self.val = x self.left = None self.right = Noneclass Solution(object): def maxPathSum(self, root): """ :type root: TreeNode :rtype: int """ self.maxSum = float('-inf') self._maxPathSum(root) return self.maxSum def _maxPathSum(self, root): if root is None: return 0 left = self._maxPathSum(root.left) right = self._maxPathSum(root.right) left = left if left > 0 else 0 right = right if right > 0 else 0 self.maxSum = max(self.maxSum, root.val + left + right) return max(left, right) + root.val
欢迎查看我的Github (https://github.com/gavinfish/LeetCode-Python) 来获得相关源码。
0 0
- *****(leetcode) Binary Tree Maximum Path Sum (tree)
- LeetCode Binary Tree Maximum Path Sum
- [Leetcode] Binary Tree Maximum Path Sum
- [leetcode] Binary Tree Maximum Path Sum
- LeetCode Binary Tree Maximum Path Sum
- [LeetCode] Binary Tree Maximum Path Sum
- leetcode Binary Tree Maximum Path Sum
- 【leetcode】Binary Tree Maximum Path Sum
- LeetCode - Binary Tree Maximum Path Sum
- [LeetCode]Binary Tree Maximum Path Sum
- [Leetcode]Binary Tree Maximum Path Sum
- Leetcode: Binary Tree Maximum Path Sum
- LeetCode-Binary Tree Maximum Path Sum
- [leetcode] Binary Tree Maximum Path Sum
- LeetCode - Binary Tree Maximum Path Sum
- LeetCode 124: Binary Tree Maximum Path Sum
- 【Leetcode】Binary Tree Maximum Path Sum
- LeetCode | Binary Tree Maximum Path Sum
- Spring MVC跳转结果的方式
- 互联网的狼性与挖井
- JSTL标签(可以直接在jsp页面格式化)
- python字典
- 31.第一个只出现一次的字符位置
- LeetCode Binary Tree Maximum Path Sum
- 模板方法
- 《自己动手写操作系统》小结
- Matlab学习 之 文件操作
- C语言中static的作用
- flask笔记:7:用户资料信息页和头像
- 党威
- 静态工厂模式
- java类似QQ的聊天室程序的实现(下)(服务器端程序)