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

Posted Z-Pilgrim

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了*Leetcode 426 & 剑指 Offer 36. 二叉搜索树与双向链表相关的知识,希望对你有一定的参考价值。

力扣

踩了一个坑,尾部结点和头结点需要连一下,因为这个坑。。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;
    
;

以上是关于*Leetcode 426 & 剑指 Offer 36. 二叉搜索树与双向链表的主要内容,如果未能解决你的问题,请参考以下文章

剑指 Offer(第 2 版)完整题解笔记 & C++代码实现(LeetCode版)

剑指 Offer(第 2 版)完整题解笔记 & C++代码实现(LeetCode版)

*leetcode 343. 整数拆分 & 剑指offer 14

*leetcode 343. 整数拆分 & 剑指offer 14

C++&Python描述 LeetCode C++&Python描述 LeetCode 剑指 Offer 22. 链表中倒数第k个节点

leetcode & 剑指 Offer 26. 树的子结构