*Leetcode 426 & 剑指 Offer 36. 二叉搜索树与双向链表

文章描述了一位程序员在力扣(LeetCode)上遇到的问题,涉及到将一棵二叉树转换成一个双链表的算法实现。在转化过程中,由于忽略了尾部节点和头结点的连接,导致运行时错误(runtimeerror)。修复这个问题的关键是确保在转化完成后,尾部节点指向头结点,头结点指向尾部节点。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

力扣

踩了一个坑,尾部结点和头结点需要连一下,因为这个坑。。runtimeerror了好久。。。

class Solution {
public:
    Node* treeToDoublyList(Node* root) {
        if(!root) return root;
        Node* head = NULL, *tail = NULL;
        // return root;
        Node* ans =  treeToDoublyList(root, head, tail);
        if(tail)tail->right = head;
        if(head)head->left = tail;
        // return ans;
        // cout << "ans:" << ans->val << endl;
        Node* ret =  ans;
        // ans->left = NULL;
        // ans->right = NULL;
        // while (ret) {
        //     cout << "&:" << ret->val << " pre:" << (ret->left == NULL ? -1:ret->left->val) << " next:" << (ret->right == NULL? -1: ret->right->val) << endl;
        //     ret = ret->right;
        // }
        
        return ans;
    }
    Node* treeToDoublyList(Node*root,  Node *&head , Node *&tail) {
        // return root;
        if(!root) {
            // head = root;
            // tail = root;
            return root;
        }
        // cout << "-->" << root->val << endl;
        
        Node* cur = NULL, *left_tail = NULL;
        if(root->left){
            cur = treeToDoublyList(root->left, cur, left_tail);
            left_tail->right = root;
            root->left = left_tail;
            tail = root;
            head =  cur;
        } else {
            cur = root;
            left_tail = root;
            head = root;
            tail = root;
        }
        //head用于
        Node*new_head = NULL, *new_tail=NULL;
        if(root->right) {
            root->right = treeToDoublyList(root->right,  new_head, new_tail);
            new_head->left = root;
            tail  = new_tail;
        } else {
            new_tail = root;
            new_head = root;
            tail = root;
        }

        if(!head || head->val > cur->val) {
            head = cur;
        }
        if(!tail || tail->val < new_tail->val) {
            tail = new_tail;
        }
        // cout << "root:" << root->val << " head:" << head->val << " tail:" << tail->val << endl;
        // cout << "<--" << root->val << endl;
        return cur;
    }
};

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值