[leetcode]Binary Tree Maximum Path Sum
来源:互联网 发布:互联网根域名 编辑:程序博客网 时间:2024/05/29 13:51
题目描述:
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
.
对于给定的二叉树,找到一条任意路径使得,这条路径上的节点和的值最大。
可以通过递归遍历二叉树,得到左右子树的最大和,如果大于0,则加入当前的sum。递归返回的时候,返回左右子树中sum更大的一个。
代码如下:
/** * Definition for binary tree * 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 maxSum=INT_MIN; dfs(root,maxSum); return maxSum; } int dfs(TreeNode *root,int &maxSum){ if(root==NULL){ return 0; } int l,r; l=dfs(root->left,maxSum); r=dfs(root->right,maxSum); int sum=root->val; if(l>0){ sum+=l; } if(r>0){ sum+=r; } maxSum=max(maxSum,sum); if(max(l,r)>0){ return max(l,r)+root->val; } else{ return root->val; } }};
0 0
- *****(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
- 吃嫩草但是农村的建设发挥女接待方面是否 扩大覆盖的
- ,跪拜雷锋劳动法避免的事方式等方面的客流高峰的某个地方客流高峰但是
- 产品详情页单栏显示
- 陈年旧事快点发货上岛咖啡vjksdfbdfb
- 真是郁闷
- [leetcode]Binary Tree Maximum Path Sum
- 黑马程序员--单例设计模式
- vjudge 之#回家了
- 安装ubuntu花屏卡死 AMD显卡
- 编译和链接
- 深入理解JavaScript单线程 定时机制
- 再谈软件测试方法之系统测试
- HDU 2732 Leapin' Lizards
- 编写一个程序,开启3个线程,这3个线程的ID分别为A、B、C,每个线程将自己的ID在屏幕上打印10遍,要求输出结果必须按ABC的顺序显示;如:ABCABC….依次递推