题解 | 树转链表

树转链表

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 {
    ListNode* tail;
    void inorder(TreeNode* root) {
        if(!root) return;
        inorder(root->left);
        auto node = new ListNode(root->val);
        tail->next = node;
        tail = tail->next;
        inorder(root->right);
    }
  public:
    ListNode* treeToList(TreeNode* root) {
        // write code here
        auto dummy_head = new ListNode(0);
        tail = dummy_head;
        inorder(root);

        return dummy_head->next;
    }
};

全部评论

相关推荐

面了100年面试不知...:今年白菜这么多,冬天可以狂吃了
点赞 评论 收藏
分享
2025-12-15 11:27
门头沟学院 Java
哇哇的菜鸡oc:所有人不要理会,就好了,后面他就知道怎么回事了,只能说有的时候市场都是被宰的人搞坏的
点赞 评论 收藏
分享
评论
点赞
收藏
分享

创作者周榜

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