Binary Tree Maximum Path Sum
来源:互联网 发布:上海嘉定装修公司知乎 编辑:程序博客网 时间:2024/05/17 22:19
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
.
解题思路:要求的是结果最大的那条路径,考虑递归遍历左右子数。
注意的地方为子树的返回值,返回的值为一条路径的最大值为max(根节点,max(根节点+左子树最大路径,根节点+右子树最大路径))
/** * 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 maxVal = INT_MIN; int maxPathSum(TreeNode *root) { if(root ==NULL){ return 0; } maxChildSum(root); return maxVal; } int maxChildSum(TreeNode *root){ int value = root->val; int lmax = 0; int rmax = 0; if(root->left){ lmax = maxChildSum(root->left); if(lmax >=0) { value += lmax; } } if(root->right){ rmax = maxChildSum(root->right); if(rmax >=0) { value += rmax; } } if(value > maxVal){ maxVal = value; } return max(root->val,max(root->val + lmax, root->val + rmax)); } };
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
- sd卡操作工具类
- Request获取用户真实IP
- SSH中Action配置成多例模式的原因
- SAX解析和生成XML文档
- ALTERA FIFO 读写verilog代码
- Binary Tree Maximum Path Sum
- 两个SYSTEMTIME比较
- HDFS添加删除节点并进行集群平衡
- Linux内核学习第2天
- 混合高斯模型(Mixtures of Gaussians)和EM算法
- 常用控件js示例
- 通过互斥锁实现数组多线程互斥插入示例
- 美团网:幸存者与通吃者
- 小学生作文