binary-tree-maximum-path-sum——二叉树任意一条路径上的最大值
2017-06-13 14:59
423 查看
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,
Return
找出任意两个节点之间的路径,并且该路径的值之和最大。
PS:关键在于递归函数的返回值,应该返回该节点的任意子节点到该节点父节点之间路径的最大值,即root->l返回的值应该为root->l的任意子节点到root能得到的最大值-root->val。同时在遍历时时刻检查sum与max的大小并更新max的值。
The path may start and end at any node in the tree.
For example:
Given the below binary tree,
1 / \ 2 3
Return
6.
找出任意两个节点之间的路径,并且该路径的值之和最大。
PS:关键在于递归函数的返回值,应该返回该节点的任意子节点到该节点父节点之间路径的最大值,即root->l返回的值应该为root->l的任意子节点到root能得到的最大值-root->val。同时在遍历时时刻检查sum与max的大小并更新max的值。
1 /** 2 * Definition for binary tree 3 * struct TreeNode { 4 * int val; 5 * TreeNode *left; 6 * TreeNode *right; 7 * TreeNode(int x) : val(x), left(NULL), right(NULL) {} 8 * }; 9 */ 10 class Solution { 11 public: 12 int maxPathSum(TreeNode *root) { 13 res=INT_MIN; 14 dfs(root); 15 return res; 16 } 17 18 int dfs(TreeNode *root){ 19 if(root==NULL){ 20 return 0; 21 } 22 int sum=root->val; 23 24 int l=dfs(root->left); 25 int r=dfs(root->right); 26 if(l>0) sum+=l; 27 if(r>0) sum+=r; 28 res=max(res,sum); 29 int tmp=max(l,r); 30 return tmp>0?tmp+root->val:root->val; 31 } 32 int res; 33 };
相关文章推荐
- Binary Tree Maximum Path Sum 二叉树中任意路径的最大和
- 【二叉树的递归】05二叉树中找任意起点和终点使他们的路径和最大【Binary Tree Maximum Path Sum】
- LeetCode(Binary Tree Maximum Path Sum) 在二叉树中找出一条和最大的路径
- LeetCode—***寻找二叉树中任意两个节点之间的最大值Binary Tree Maximum Path Sum
- [LeetCode] Binary Tree Maximum Path Sum 求二叉树的最大路径和
- LeetCode OJ:Binary Tree Maximum Path Sum(二叉树最大路径和)
- Binary Tree Maximum Path Sum 求二叉树的最大路径和
- LeetCode-Binary Tree Maximum Path Sum-二叉树最大路径和-DFS
- JavaShowAlgorithm-Binary Tree Maximum Path Sum 二叉树最大路径和
- LeetCode(124) Binary Tree Maximum Path Sum 二叉树的最大路径和 (如何递归?)
- [Leetcode] Binary tree maximum path sum求二叉树最大路径和
- Leetcode 124 Binary Tree Maximum Path Sum 二叉树最大路径和
- [LintCode] Binary Tree Maximum Path Sum (二叉树中的最大路径和)
- 124 Binary Tree Maximum Path Sum 求二叉树的最大路径和
- Binary Tree Maximum Path Sum 二叉树最大路径和 @LeetCode
- 二叉树最大路径和-Binary Tree Maximum Path Sum
- binary-tree-maximum-path-sum(二叉树的最大路径和)
- Binary Tree Maximum Path Sum (二叉树路径和的最大值) 【leetcode】
- LeetCode | Binary Tree Maximum Path Sum(二叉树的路径最大值)
- [LeetCode 124] - 二叉树最大路径和(Binary Tree Maximum Path Sum)