You signed in with another tab or window. Reload to refresh your session.You signed out in another tab or window. Reload to refresh your session.You switched accounts on another tab or window. Reload to refresh your session.Dismiss alert
int maxSum;
int Max(int a, int b){
return a > b ? a : b;
}
int Dfs(struct TreeNode* node){
if(node == NULL){
return 0;
}
int sum1 = Max(Dfs(node->left), 0);
int sum2 = Max(Dfs(node->right), 0);
int current = sum1 + sum2 + node->val;
maxSum = Max(maxSum, current);
return node->val + Max(sum1, sum2);
}
int maxPathSum(struct TreeNode* root){
maxSum = INT_MIN;
Dfs(root);
return maxSum;
}
The text was updated successfully, but these errors were encountered:
路径 被定义为一条从树中任意节点出发,沿父节点-子节点连接,达到任意节点的序列。同一个节点在一条路径序列中 至多出现一次 。该路径 至少包含一个 节点,且不一定经过根节点。
路径和 是路径中各节点值的总和。
给你一个二叉树的根节点 root ,返回其 最大路径和 。
示例 1:
输入:root = [1,2,3]
输出:6
解释:最优路径是 2 -> 1 -> 3 ,路径和为 2 + 1 + 3 = 6
示例 2:
输入:root = [-10,9,20,null,null,15,7]
输出:42
解释:最优路径是 15 -> 20 -> 7 ,路径和为 15 + 20 + 7 = 42
提示:
树中节点数目范围是 [1, 3 * 104]
-1000 <= Node.val <= 1000
思路:递归
确定一个节点的左右子节点 各自可能达到的最大值,(注意与0作对比,如小于0,则放弃这一子节点)
然后确定当前节点的可能最大值(max(左,右)+ current->val)
The text was updated successfully, but these errors were encountered: