leetcode---binary-tree-maximum-path-sum---树
2017-10-06 16:11
417 查看
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.
The path may start and end at any node in the tree.
For example:
Given the below binary tree,
1
/ \
2 3
Return6.
/** * 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 ans; int dfs(TreeNode *root) { if(!root) return 0; int lmax = dfs(root->left); int rmax = dfs(root->right); int v = max(root->val, max(root->val+lmax, root->val+rmax)); int v1 = max(v, root->val+lmax+rmax); if(v1 > ans) ans = v1; return v; } int maxPathSum(TreeNode *root) { ans = INT_MIN; dfs(root); return ans; } };
相关文章推荐
- LeetCode - Binary Tree Maximum Path Sum
- leetcode Binary Tree Maximum Path Sum 迭代算法
- leetcode-124:Binary Tree Maximum Path Sum(Java)
- [LeetCode] Binary Tree Maximum Path Sum 求二叉树的最大路径和
- leetcode第27题(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 Solution
- 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 (树的直径 DFS 推荐)
- leetcode-Binary Tree Maximum Path Sum
- [LeetCode]Binary Tree Maximum Path Sum
- [leetcode-124]Binary Tree Maximum Path Sum(c++)
- LeetCode-Binary Tree Maximum Path Sum
- [LeetCode] Binary Tree Maximum Path Sum(最大路径和)
- LeetCode Binary Tree Maximum Path Sum