二叉树中最大路径和
2017-02-07 21:28
190 查看
分治,动态规划。
分析:最长的路径一定经过某一个点,并且以这一个点为根节点;所以可以动态遍历每一个节点,找到使路径和最大的根节点。
C++代码:
看网友的更简洁的方法:
在一个函数的不断递归中处理了最后的最大值ret,还要在最后返回一root为根节点的最大的一边值。
分析:最长的路径一定经过某一个点,并且以这一个点为根节点;所以可以动态遍历每一个节点,找到使路径和最大的根节点。
C++代码:
/** * Definition of TreeNode: * class TreeNode { * public: * int val; * TreeNode *left, *right; * TreeNode(int val) { * this->val = val; * this->left = this->right = NULL; * } * } */ class Solution { public: /** * @param root: The root of binary tree. * @return: An integer */ int maxPathSum(TreeNode *root) { if (root == NULL) { return 0; } vector<int> res; maxRoot(root,res); int a = res[0]; for(auto i : res){ if (i > a) { a = i; } } return a; } void maxRoot(TreeNode * root, vector<int> &res) { if (root == NULL ) { return; } int l = maxLink(root->left); int r = maxLink(root->right); res.push_back(max(0,l) + max(0,r) + root->val); maxRoot(root->left,res); maxRoot(root->right,res); } int maxLink(TreeNode * root) { if (root == NULL) { return 0; } return root->val + max(0,max(maxLink(root->left),maxLink(root->right))); } };
看网友的更简洁的方法:
在一个函数的不断递归中处理了最后的最大值ret,还要在最后返回一root为根节点的最大的一边值。
class Solution { public: /** * @param root: The root of binary tree. * @return: An integer */ int maxPathSum(TreeNode *root) { // write your code here int ret = INT_MIN; onePath(root,ret); return ret; } int onePath(TreeNode* root,int&ret) { if(root==nullptr) return 0; int l = onePath(root->left,ret); int r = onePath(root->right,ret); ret = max(ret,max(0,l)+max(0,r)+root->val); return max(0,max(l,r))+root->val; } };
相关文章推荐
- 二叉树的最大路径和与最远结点距离
- [各种面试题] 非二叉树的最大路径和
- [阿里] 给定二叉树,每条边都有权值 , 求二叉树中的最大路径
- LeetCode之求二叉树最大路径和
- lintcode binary-tree-maximum-path-sum 二叉树中的最大路径和
- 【二叉树】最大路径和【124. Binary Tree Maximum Path Sum】
- java编程求二叉树最大路径问题代码分析
- LeetCode OJ:Binary Tree Maximum Path Sum(二叉树最大路径和)
- 二叉树中的最大路径和
- 求一颗二叉树中叶子节点间最大的路径长度
- lintcode,二叉树中的最大路径和
- [Leetcode] Binary tree maximum path sum求二叉树最大路径和
- LeetCode-Binary Tree Maximum Path Sum-二叉树最大路径和-DFS
- 【数据结构机试复习7】 二叉树 & 二叉树最大路径
- 二叉树系列---求二叉树的最大路径和
- 二叉树中的最大路径和
- LeetCode 124. Binary Tree Maximum Path Sum(二叉树最大路径和)
- LeetCode(124) Binary Tree Maximum Path Sum 二叉树的最大路径和 (如何递归?)
- 每天一道LeetCode-----计算二叉树的最大路径和,路径只需要从一个节点到达另一个节点,无其他要求
- 二叉树最大路径和