[leetcode]Binary Tree Maximum Path Sum
来源:互联网 发布:中国近几年进出口数据 编辑:程序博客网 时间:2024/05/01 19:35
Description
Problem Link
对于给定的二叉树,求最大路径长度。HINT:不一定要经过根节点。
例如下图,最大路径为8->-3->11
Possible Solution
遍历二叉树:计算以当前节点为中间节点,连接左右子树的最大路径,并返回经过当前结点向左/右子树走的最大路径。例如上图中,以-3为连结的最大路径是8->-3->11,遍历-3这个结点,返回值是11+-3 =8。
附代码
/** * 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 {private: static const int INF = 0x3F3F3F3F; int ans; int traverse(TreeNode *root) { if (root == NULL) return -INF; int leftval = traverse(root -> left); int rightval = traverse(root -> right); int ans = root -> val; if (leftval > 0) ans += leftval; if (rightval > 0) ans += rightval; if (ans > this -> ans) this-> ans = ans; int maxval = std::max(leftval, rightval); return root -> val + (maxval > 0 ? maxval : 0); }public: int maxPathSum(TreeNode* root) { this->ans = -INF; this->traverse(root); return this->ans; }};
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
- 实验记录:Oracle redo logfile的resize过程
- Ubuntu PPA用法简介
- ML-kNN 多标签k近邻算法
- 观察者模式!
- V4L2框架分析学习
- [leetcode]Binary Tree Maximum Path Sum
- RadioButton和CheckBox
- 59. web 攻击技术(3)
- HashMap源码解析-jdk8
- POJ_2386_Lake Counting
- CSDN-markdown编辑器快捷方式
- mysql数据库配置
- 蓝桥杯 算法训练 最短路 spfa
- Unrecognized Windows Sockets error: 0: JVM_Bind 异常解决办法