124. Binary Tree Maximum Path Sum
来源:互联网 发布:c语言经典编程题 编辑:程序博客网 时间:2024/06/04 18:49
这道题给一个二叉树,要求最大的一条路径,这条路径必须沿着parent-child,但是可以是从任意节点到任意节点的。
遇到树的问题大多可以用递归来做,这个题也是二叉树的遍历,所以想到DFS。
遍历这棵树,遍历到节点root的时候,最大的路径有三种可能:
(1)左子树最大路径+root
(2)右子树最大路径+root
(3)左子树最大路径+root+右子树最大路径
(4)root
这里注意两个问题:一个是上述第(4)种情况,如果root的左子树和右子树都是小于0的数,那么最大路径肯定是root本身。还有一个很关键的问题,要求root最大路径,我们肯定要知道root->left最大路径和root->right最大路径,然后比较上述四种情况哪个最大,但是如果root->left的最大路径是root->left->left + root-left + root->left->right,那么这个路径不能用作找root最大路径,因为这个路径与root不能构成一条合法的路径,所以我们只能用这个路径来更新res,但是返回给上一级(root)的路径只能是上述(1)(2)(4)中的一条。于是就有了下面程序的这个return。
/** * Definition for a binary tree node. * struct TreeNode { * int val; * TreeNode *left; * TreeNode *right; * TreeNode(int x) : val(x), left(NULL), right(NULL) {} * }; */class Solution {public: int maxPathSum(TreeNode* root) { int res = INT_MIN; helper(root, res); return res; } int helper(TreeNode* root, int& res){ if(root == NULL) return 0; int left = helper(root->left, res); int right = helper(root->right, res); int top = max(left, 0) + max(right, 0) + root->val; res = max(res, top); //return max(left, right) + root->val; return max(left, right) > 0 ? max(left, right) + root->val : root->val; }};
阅读全文
0 0
- Tree-----124. Binary Tree Maximum Path Sum
- LeetCode 124. Binary Tree Maximum Path Sum
- [LeetCode]*124.Binary Tree Maximum Path Sum
- [Leetcode] 124. Binary Tree Maximum Path Sum
- [leetcode] 124. Binary Tree Maximum Path Sum
- 124. Binary Tree Maximum Path Sum
- [leetcode] 124. Binary Tree Maximum Path Sum
- Leetcode 124. Binary Tree Maximum Path Sum
- Leetcode 124. Binary Tree Maximum Path Sum
- LeetCode 124. Binary Tree Maximum Path Sum
- leetcode 124. Binary Tree Maximum Path Sum
- LeetCode 124. Binary Tree Maximum Path Sum
- 124. Binary Tree Maximum Path Sum
- 124. Binary Tree Maximum Path Sum
- Leetcode 124. Binary Tree Maximum Path Sum
- [LeetCode] 124. Binary Tree Maximum Path Sum
- 124. Binary Tree Maximum Path Sum
- leetcode 124.Binary Tree Maximum Path Sum
- (一) Hyperledger Fabric在CentOS 7.2 64位系统的开发环境搭建
- 图像识别与处理之Opencv——Mat表达式的运算(矩阵的一些运算)
- oracle odbc驱动不支持BIGINT,需使用其他类型代替
- Linux CentOS 7×64 & JDK 1.8.0_11 安装与配置
- 题目:输出张三李四的姓名,年龄,地址,性别以及体重
- 124. Binary Tree Maximum Path Sum
- 安卓API指南之Intent 和 Intent 过滤器
- apicloud div 滚动到顶部
- iOS中根据视图生成图片,裁剪图片
- 封装的基类activity
- python 读写csv
- 开机广告页面2017流行样式 dialogTheme的popuwindow版本
- Asp.net运行机制
- 读懂MySQL执行计划