Skip to content
Rain Hu's Workspace
Go back

[LeetCode] 124. Binary Tree Maximum Path Sum

Rain Hu

124. Binary Tree Maximum Path Sum


一、題目

Example 1:
exx1

Example 2: exx2

Constraints:


二、分析

三、解題

1. DFS

int res = INT_MIN;
int maxPathSum(TreeNode* root) {
    dfs(root);
    return res;
}
int dfs(TreeNode* root) {
    if (!root) return 0;
    int left = dfs(root->left);
    int right = dfs(root->right);
    int sum = root->val + max(left, 0) + max(right, 0);
    res = max(res, sum); 
    return root->val + max(max(left, 0) + max(right, 0));
}

回目錄 Catalog


Share this post on:

Previous
[LeetCode] 2500. Delete Greatest Value in Each Row
Next
[LeetCode] 1339. Maximum Product of Splitted Binary Tree