leetcode No124. Binary Tree Maximum Path Sum
来源:互联网 发布:淘宝抢红包微信群 编辑:程序博客网 时间:2024/06/06 07:28
Question
Given a binary tree, find the maximum path sum.
For this problem, a path is defined as any sequence of nodes from some starting node to any node in the tree along the parent-child connections. The path must contain at least one node and does not need to go through the root.
For example:
Given the below binary tree,
1 / \ 2 3
Return 6.
Algorithm
可以用递归做,同时更新最大长度maxLength
假设左子树最长路径和(这里指的是dfs的路径)为l
假设右子树最长路径和(这里指的是dfs的路径)为r
因为负数不会增加路径和反而会减小,所以要和0比较
maxLength=max(maxLength,l+r+root->val)
Accepted Code
/** * 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) { if(root == NULL) return 0; int res=INT_MIN; helper(root,res); return res; } int helper(TreeNode* root,int &res){ if(root==NULL) return 0; int l=max(0,helper(root->left,res)); int r=max(0,helper(root->right,res)); res=max(res,l+r+root->val); return l>r?l+root->val:r+root->val; }};
阅读全文
0 0
- leetcode No124. Binary Tree Maximum Path Sum
- *****(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
- spring mvc 数据绑定问题 提交表单提示HTTP status 400, The request sent by the client was syntactically incorrect
- 通过x-shell向云服务器上传文件
- spring学习--总结IOC(控制反转)
- Javascript----Promise初步探究
- 如果你在学嵌入式底层驱动,内核模块编程将是你的第一课!小白学Linux之内核模块编程详解
- leetcode No124. Binary Tree Maximum Path Sum
- C语言读写SQLite数据库
- centOS7下redis3.0安装以及布置集群教程(单机创建多个实例调试)
- Android开发中的五大布局
- log4j日志记录配置的小结
- POJ 1972 Dice Stacking 笔记
- Vim插件之Conque GDB
- mysql表的操作
- RDD编程