【leetcode】binary-tree-maximum-path-sum
2017-06-21 15:32
295 查看
题目 :
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,
Return6.
题目解答:
给定一个二叉树,找到最大路径和。
路径可以在树的任何节点上开始和结束。
例如:
给定下面的二叉树,
1
/ \
2 3
Return6。
内部问题罗列:
最后的大问题答案,可能的路径出处有 :
1、root +left路径;
2、root +right路径;
3、root + right路径 +left 路径;
4、root单个的结点;
写代码过程中可能遇到的问题遇到的问题:
1、结点的值可能是负数;所以最大路径的初始值需要设定为最小值;
2、在子树节点上返回的最大的路径和不能出现第三种情况(解决方法:我们需要保存这哥知道最大的路径max之中);
代码实现:
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
Return6.
题目解答:
给定一个二叉树,找到最大路径和。
路径可以在树的任何节点上开始和结束。
例如:
给定下面的二叉树,
1
/ \
2 3
Return6。
内部问题罗列:
最后的大问题答案,可能的路径出处有 :
1、root +left路径;
2、root +right路径;
3、root + right路径 +left 路径;
4、root单个的结点;
写代码过程中可能遇到的问题遇到的问题:
1、结点的值可能是负数;所以最大路径的初始值需要设定为最小值;
2、在子树节点上返回的最大的路径和不能出现第三种情况(解决方法:我们需要保存这哥知道最大的路径max之中);
代码实现:
/** * Definition for binary tree * struct TreeNode { * int val; * TreeNode *left; * TreeNode *right; * TreeNode(int x) : val(x), left(NULL), right(NULL) {} * }; */ #include<limits.h> class Solution { public: int _maxPathSum(TreeNode *root,int &max) { //要是当前的结点是空 if(root == NULL) { return 0; } //得到当前结点的左右子树的最大的路径和 int left = _maxPathSum(root->left,max) ; int right = _maxPathSum(root->right,max) ; int data = root->val; int sum = left+right+data; //更新max的值 max = max < (left+data)?(left+data):max; max = max < (right+data)?(right+data):max; max = max < data?data:max; max = max < sum?sum:max; //得到返回值 int ret = data; ret = ret < left+data?left+data:ret; ret = ret < right +data?right+data:ret; return ret; } int maxPathSum(TreeNode *root) { if(root == NULL) { return 0; } //设置max值为最小的int值 int max = 0x80000000; _maxPathSum(root,max); return max; } };
相关文章推荐
- leetcode:Binary Tree Maximum Path Sum
- [LeetCode] Binary Tree Maximum Path Sum
- LeetCode124—Binary Tree Maximum Path Sum
- [LeetCode]Binary Tree Maximum Path Sum
- 算法分析与设计丨第十八周丨LeetCode(21)——Binary Tree Maximum Path Sum(Hard)
- leetcode--Binary Tree Maximum Path Sum
- leetcode- Binary Tree Maximum Path Sum
- 【Leetcode-Hard-124】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
- [leetcode]Binary Tree Maximum Path Sum
- [LeetCode] Binary Tree Maximum Path Sum
- *Leetcode_binary-tree-maximum-path-sum (updated c++ and python version)
- leetcode-Binary Tree Maximum Path Sum
- LeetCode力扣之124. Binary Tree Maximum Path Sum
- Binary Tree Maximum Path Sum(leetcode)
- [LeetCode] Binary Tree Maximum Path Sum(递归)
- LeetCode-Binary Tree Maximum Path Sum