首页 > 代码库 > 【leetcode】Binary Tree Maximum Path Sum
【leetcode】Binary Tree Maximum Path Sum
Binary Tree Maximum Path Sum
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
Return 6
.
用递归确定每一个节点作为root时,从root出发的最长的路径
在每一次递归中计算maxPath
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 maxSum=INT_MIN;13 int maxPathSum(TreeNode *root) {14 15 DFS(root);16 return maxSum;17 }18 19 int DFS(TreeNode *root)20 {21 if(root==NULL)22 {23 return 0;24 }25 26 int left=DFS(root->left);27 int right=DFS(root->right);28 29 int sum=root->val;30 if(left>0) sum+=left;31 if(right>0) sum+=right;32 if(maxSum<sum) maxSum=sum;33 34 return (left>0||right>0)?root->val+max(left,right):root->val;35 }36 };
【leetcode】Binary Tree Maximum Path Sum
声明:以上内容来自用户投稿及互联网公开渠道收集整理发布,本网站不拥有所有权,未作人工编辑处理,也不承担相关法律责任,若内容有误或涉及侵权可进行投诉: 投诉/举报 工作人员会在5个工作日内联系你,一经查实,本站将立刻删除涉嫌侵权内容。