[LeetCode] Binary Tree Maximum Path Sum
来源:互联网 发布:乾隆知画嗯嗯 编辑:程序博客网 时间:2024/06/03 14:33
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
.
这道题其实跟求二叉树的深度类似,只不过需要求是带权值的深度而已,即所说的path sum。对于任意一个节点,其对应的path sum应该等于:其左子树节点的带权值深度 + 其右子树的带权值深度 + 其自身的值。而带权值的深度求法和一般的深度求法类似,就是取子节点带权值的深度的那个,加上自身的值即可。
这里需要注意的是,由于题目中没有说明所有节点的值都为非负数,所以得考虑负数的存在。如果一旦深度为负值,那么计算path sum的时候还不如不加子节点的带权值深度,所以这里每次计算出的带权值的深度,我都会跟0比较,如果比0小,那么我就取0。
// given a nonempty node, retrieve the weighted depth and update the max path sumint weightedDepth(TreeNode *root, int & maxPathSum) {int leftPathSum = 0, rightPathSum = 0;if (root->left) leftPathSum = max(0, weightedDepth(root->left, maxPathSum));if (root->right) rightPathSum = max(0, weightedDepth(root->right, maxPathSum));// update the max path summaxPathSum = max(maxPathSum, leftPathSum + root->val + rightPathSum);return max(leftPathSum + root->val, rightPathSum + root->val);} int maxPathSum(TreeNode *root) {if (!root) return 0;int maxPathSum = INT_MIN;weightedDepth(root, maxPathSum);return maxPathSum;}
- *****(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
- 黑马程序员_HashCode()方法的作用?以及在HashSet集合中的使用
- 跟踪导弹轨迹的向量计算
- 已知一按升序排好的包含有10个元素的数组,将某一整数插入到该数组中
- Mega2560
- Duff's Device
- [LeetCode] Binary Tree Maximum Path Sum
- 体系架构片
- UVA 10714 (13.11.07)
- 黑马程序员_了解JavaBean
- 基于arduino mega2560的飞控,APM、MWC or 海盗。九阳神功才练到第一层,还要闭关修炼
- 长英文自动换行的最终解决方法
- 将任意一整数插入到数组中,插入位置由用户由键盘输入。
- android中的计算器应用
- photoshop另存为jpg和web格式的区别