Binary Tree Maximum Path Sum
来源:互联网 发布:淘宝app收藏店铺 编辑:程序博客网 时间:2024/05/16 01:28
LeetCode :Binary Tree Maximum Path Sum
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
.
解题思路:对于树中的任意节点来说,包括该节点在内的路径和可以表示为:node.val + F(node->left) + F(node->right),即:节点值+左子树的路径和+右子树的路径和(其中F(node->left)表示node左子树路径和),这是一个递归的定义。找出最大和就是需要的结果。
class Solution {int maxPathSum_dfs(TreeNode* root, int *maxSum){if (NULL == root){return 0;}//求出节点root的左子树的路径和、右子树的路径和int l = maxPathSum_dfs(root->left, maxSum);int r = maxPathSum_dfs(root->right, maxSum);//如果子树路径和小于零则归零,因为如果子树路径和小于零,则不会累加到路径和当中if (l < 0) l = 0;if (r < 0) r = 0;//判断root->val + F(root->left) + F(root->right)是否大于当前保存的最大值if (l + r + root->val > *maxSum)*maxSum = l + r + root->val;//返回路径和(由于返回的是路径,因此只能从左子树和右子树当中选一个较大的路径和返回)return root->val + (l>r ? l : r);}public:int maxPathSum(TreeNode *root) {int maxSum = INT_MIN;maxPathSum_dfs(root, &maxSum);return maxSum;}};
0 0
- Binary Tree Maximum Path Sum
- Binary Tree Maximum Path Sum
- Binary Tree Maximum Path Sum
- Binary Tree Maximum Path Sum
- Binary Tree Maximum Path Sum
- Binary Tree Maximum Path Sum
- Binary Tree Maximum Path Sum
- Binary Tree Maximum Path Sum
- Binary Tree Maximum Path Sum
- Binary Tree Maximum Path Sum
- Binary Tree Maximum Path Sum
- Binary Tree Maximum Path Sum
- Binary Tree Maximum Path Sum
- Binary Tree Maximum Path Sum
- Binary Tree Maximum Path Sum
- Binary Tree Maximum Path Sum
- Binary Tree Maximum Path Sum
- Binary Tree Maximum Path Sum
- 23种设计模式 (一) 创建型模式
- 如何屏蔽流氓宽带商在你的页面里面强行插入的广告代码
- Android三十个月入门到精通 -- 第二范式
- 请求重定向、请求转发、请求包含
- (转)TCP/IP三次握手与四次挥手_老六_新浪博客
- Binary Tree Maximum Path Sum
- 启动其他application的组件遇到的小问题 - SecurityException
- 一个有n个整数的递增有序数组。对它进行向左或向右循环移动若干次后,要求给出一个代码实现,尽可能快地从这个数组中寻找指定值所在的位置
- 《javascript高级程序设计》读书笔记
- struts2工作流程(请求响应流程)
- ios8 中过期的一些方法 通讯录 推送
- __declspec(dllimport)的作用
- log4j 日志配置 properties 和 xml形式两种
- 面试题,说说你对spring IOC和AOP的理解