Given a binary tree, find the maximum path sum.
The path may start and end at any node in the tree.
For example:
Given the below binary tree,
1
/ \
2 3
Return 6
.
- allsum代表穿过当前节点的路径(左边一支儿+自己节点+右边一支儿)。
- 注意树的节点可以是负数,所以allsum不一定是最长的。
- 每次return以root(当前节点)开头最大的单只path sum。
Solution:
private int maxHere = Integer.MIN_VALUE; public int maxPathSum(TreeNode root) { if(root == null) return 0; maxSingleSideSum(root); return maxHere; } public int maxSingleSideSum(TreeNode root) { if(root == null) return 0; int leftSum = maxSingleSideSum(root.left); int rightSum = maxSingleSideSum(root.right); // 自己,自己+左,自己+右 int childMax = Math.max(leftSum, rightSum); int retMax = Math.max(root.val, root.val+childMax); //自己+左+右 int allsum = root.val+leftSum+rightSum; maxHere = Math.max(maxHere, Math.max(allsum, retMax)); return retMax; }
相关推荐
leetcode-tag-Tree
《leetcode-solutions》,刷算法题,需要有一定的英文阅读能力。。。
Algorithm-LeetCode-Sol-Res.zip,干净,易懂的解决方案和资源,为leetcode在线判断算法问题。,算法是为计算机程序高效、彻底地完成任务而创建的一组详细的准则。
Algorithm-leetcode-spider.zip,leetcode公司,算法是为计算机程序高效、彻底地完成任务而创建的一组详细的准则。
leetcode-cli-plugins leetcode-cli 的第 3 方插件。 什么是 如何使用 如何使用 插件 名称 描述 增强的命令 按公司或标签过滤问题 list 不要在同一台计算机上使 Chrome 的会话过期 login 不要在同一台计算机上使 ...
在IDE中解决LeetCode问题,支持leetcode.com与leetcode-cn.com,满足基本的做题需求。 理论上支持: IntelliJ IDEA PhpStorm WebStorm PyCharm RubyMine AppCode CLion GoLand DataGrip Rider MPS Android Studio。
cauly-rust-leetcode-utils={path="path/to/cauly-rust-leetcode-utils"} 使用来自 cauly-rust-leetcode-utils 的数据结构(“使用 cauly_rust_leetcode_utils::..”) 运行cargo run --manifest-path=path/to/cauly...
主要介绍了LeetCode -- Path Sum III分析及实现方法的相关资料,希望通过本文能帮助到大家,需要的朋友可以参考下
解题思路思路和LeetCode-python 503.下一个更大元素 II一致,只是这里求的是下标的距离,而不是数值倒序搜索,用到栈,栈里存储索引情况1:若栈为
LeetCode-BinarySearch
leetcode 答案解析 golang解答
leetcode-cheat 的发布 它是什么 ? 这是一个chrome 扩展,可以帮助您更高效地使用 leetcode。您可以从 重要: leetcode-cheat 现在只支持中文版。 也就是说不完全支持leetcode.com,但是你可以用leetcode-cn.com代替...
~/.vscode/extensions/leetcode.vscode-leetcode-0.17.0/node_modules/vsc-leetcode-cli/bin/leetcode /usr/local/bin/leetcode 修改模板 open ~/.vscode/extensions/leetcode.vscode-leetcode-0.17.0/node_modules/...
leetcode卡leetcode 二叉树卡片 LeetCode 二叉树卡片问题的章节智解
leetcode-editor,在ide中做leetcode练习,支持leetcode.com和leetcode-cn.com,以满足练习的基本需求。理论上支持:intellij idea phpstorm webstorm pycharm rubymine appcode clion goland datagrip rider mps ...
leetcode-helper-1.7.1
leetcode-tag-dynamic programming
假设数组长度为N,准备N+1个桶,把max放在N+1号桶,nums中在[min,max)范围上的数放在1~N号桶中,对于1 ~ N号桶的每一个桶来说,负责的区间
然后进入到LeetCode-Spider目录中修改config.json,其中outputDir需要填写该工程的/docs/views文件夹路径 { "username": "aaa", "password": "bbb", "outputDir": "/Users/liuyao/Downloads/LeetCode-Blog-Test/docs...