题解 | 树转链表

树转链表

https://www.nowcoder.com/practice/adf889912fa441ea80a7c038baa1e2bb

/*
struct TreeNode {
    int val;
    struct TreeNode *left;
    struct TreeNode *right;
    TreeNode(int x) :
            val(x), left(NULL), right(NULL) {
    }
};*/
/*
struct ListNode {
    int val;
    struct ListNode *next;
    ListNode(int x) : val(x), next(NULL) {}
};*/
class Converter {
  public:
    ListNode* treeToList(TreeNode* root) {
        // write code here
        if (!root) return nullptr;
        auto dummy_root = new ListNode(0);
        dummy_root->next = treeToList(root->left);
        auto cur = dummy_root;
        while (cur->next) {
            cur = cur->next;
        }
        cur->next = new ListNode(root->val);
        cur = cur->next;
        cur->next = treeToList(root->right);
        return dummy_root->next;
    }
};

全部评论

相关推荐

2025-12-25 16:26
已编辑
河北科技学院 Java
勇敢的牛油不服输:2800-300那不等于2500一个月吗兄弟们
点赞 评论 收藏
分享
评论
点赞
收藏
分享

创作者周榜

更多
牛客网
牛客网在线编程
牛客网题解
牛客企业服务