leetcode Binary Tree Maximum Path Sum

本文详细介绍了在解决BinaryTreeMaximumPathSum问题时遇到的误解,并分享了如何通过多种方式优化代码,从冗长复杂到简洁高效。通过对比不同版本的实现,展示了如何在保持代码可读性的同时提升性能。

Binary Tree Maximum Path Sum

  Total Accepted: 3538   Total Submissions: 19408 My Submissions

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.


I'm ashamed of mistakes I made because I misunderstood the meaning of path. The path is a chain instead of a subtree.  # stands for Null, the following is the wrong code :

/**
 * 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 max3(int a,int b,int c){
        int max1=max(a,b);
        int max2=max(max1,c);
        return max2;
    }
    int maxPathSum(TreeNode *root) {
        // Note: The Solution object is instantiated only once and is reused by each test case.
        if(root==NULL)
            return 0;
        int l,r,max1,max2,maxV,v;
        max1=max2=v=root->val;
        if(root->left!=NULL){
            l=maxPathSum(root->left);
            max1=max3(l,v,l+v);
        }
        if(root->right!=NULL){
            r=maxPathSum(root->right);
            max2=max3(r,v,r+v);         
        }
        if(root->left!=NULL&&root->right!=NULL)
            maxV=max3(max1,max2,l+r+v);
        else
            maxV=max(max1,max2);
        return maxV;
    }
};


 I changed the code in the following way, whereas the code is still lengthy:

/**
 * 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 max3(int a,int b,int c){
        int max1=max(a,b);
        int max2=max(max1,c);
        return max2;
    }
    int max4(int a,int b,int c,int d){
        int max1=max(a,b);
        int max2=max(c,d);
        int max3=max(max1,max2);
        return max3;
    }    
    int DFS(TreeNode *root,int &res){
        
        int l=0,r=0,max1,max2,maxV,v;
        max1=max2=v=root->val;
        if(root->left!=NULL){
            l=DFS(root->left,res);
            max1=max3(l,v,l+v);
        }
        if(root->right!=NULL){
            r=DFS(root->right,res);
            max2=max3(r,v,r+v);         
        }
        if(root->left!=NULL&&root->right!=NULL)
            res=max4(max1,max2,l+r+v,res);
        else
            res=max3(max1,max2,res);
        return max3(v,v+l,v+r);        
    }
    int maxPathSum(TreeNode *root) {
        // Note: The Solution object is instantiated only once and is reused by each test case.
        int res;
        if(root==NULL)
            return 0;
        else{
            res=root->val;
            DFS(root,res);
        }
        return res;
    }
};

I find another concise version from the Internet like that:

/**
 * 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 res=0;
    int DFS(TreeNode *root){
        if(root==NULL)  return 0;
        int l=DFS(root->left);
        int r=DFS(root->right);
        int v=root->val;
        if(l>0) v+=l;
        if(r>0) v+=r;
        if(v>res) res=v;
        return max(root->val+max(l,r),root->val);
    }
    int maxPathSum(TreeNode *root) {
        // Note: The Solution object is instantiated only once and is reused by each test case.
        if(root==NULL)  return 0;
        res=root->val;
        DFS(root);
        return res;
    }
};



 

 

这段代码是一个经典的 **二叉树中的最大路径和**(LeetCode 第124题)的解法,使用了 **DFS(深度优先搜索) + 动态规划思想**。 你提供的代码使用了 C++14 以后的特性,如 **lambda 表达式递归(`this auto&& dfs`)** 和 **立即调用 lambda** 的方式来实现递归 DFS。这种写法在 LeetCode 等 OJ 平台上非常常见,但如果你希望在 **Visual Studio(VS)等标准编译器下编译运行**,这段代码 **可能无法通过编译**,因为 `this auto&& dfs` 这种写法不是标准 C++,而是某些编译器的扩展(比如 GCC 支持,但 MSVC 不支持)。 --- ### ✅ VS 兼容的完整版本(标准 C++17 写法) 下面是可以在 Visual Studio 上正常编译运行的完整版本: ```cpp #include <iostream> #include <algorithm> #include <climits> using namespace std; // Definition for a binary tree node. struct TreeNode { int val; TreeNode *left; TreeNode *right; TreeNode(int x) : val(x), left(nullptr), right(nullptr) {} }; class Solution { public: int maxPathSum(TreeNode* root) { int ans = INT_MIN; dfs(root, ans); return ans; } private: // 返回以当前节点为结尾的最大路径链和 int dfs(TreeNode* node, int& ans) { if (!node) return 0; // 递归左右子树 int left_gain = max(dfs(node->left, ans), 0); // 只取正值 int right_gain = max(dfs(node->right, ans), 0); // 当前节点作为最高点,计算路径和 int current_path_sum = left_gain + right_gain + node->val; ans = max(ans, current_path_sum); // 返回当前节点的最大链和(只能选一边) return max(left_gain + node->val, right_gain + node->val); } }; ``` --- ### ✅ 示例 main 函数(用于测试) ```cpp int main() { // 构造一个测试二叉树: // 1 // / \ // 2 3 TreeNode* root = new TreeNode(1); root->left = new TreeNode(2); root->right = new TreeNode(3); Solution sol; cout << "Maximum Path Sum: " << sol.maxPathSum(root) << endl; // 输出 6 // 清理内存 delete root->left; delete root->right; delete root; return 0; } ``` --- ### ✅ VS 编译注意事项: - **不支持 `this auto&& dfs` 写法**(这是 GCC 的扩展)。 - 使用标准的类成员函数或普通函数来递归是兼容性更好的方式。 - 使用 `std::function` 也可以实现递归 lambda,但效率略低。 --- ### ✅ 使用 `std::function` 的版本(兼容性较好) ```cpp #include <functional> int maxPathSum(TreeNode* root) { int ans = INT_MIN; function<int(TreeNode*)> dfs = [&](TreeNode* node) { if (!node) return 0; int l = max(dfs(node->left), 0); int r = max(dfs(node->right), 0); ans = max(ans, l + r + node->val); return max(l, r) + node->val; }; dfs(root); return ans; } ``` --- ###
评论
成就一亿技术人!
拼手气红包6.0元
还能输入1000个字符
 
红包 添加红包
表情包 插入表情
 条评论被折叠 查看
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值