C++二叉搜索树转换成双向循环链表(双指针或数组)

在这里插入图片描述
本文解法基于性质:二叉搜索树的中序遍历为 递增序列 。

将 二叉搜索树 转换成一个 “排序的循环双向链表” ,其中包含三个要素:
1.排序链表: 节点应从小到大排序,因此应使用 中序遍历
2.“从小到大”访问树的节点。 双向链表: 在构建相邻节点的引用关系时,设前驱节点 pre 和当前节点 cur ,
不仅应构建 pre.right= cur ,也应构建 cur.left = pre 。
3.循环链表: 设链表头节点 head 和尾节点 tail ,则应构建 head.left = tail 和 tail.right = head 。

双指针:

class Solution {
    
    
private:
    Node* head, * pre = NULL;
public:
    Node* treeToDoublyList(Node* root) {
    
    //双指针做法
        if (!root) return NULL;
        inorder(root);
        head->left = pre;
        pre->right = head;
        return head;
    }
    void inorder(Node* root)
    {
    
    
        if (root == NULL)return;
        inorder(root->left);
        root->left = pre;
        if (pre)
            pre->right = root;
        else head = root;
        pre = root;
        inorder(root->right);
    }
};

数组方法:很简单就不做介绍了,就是先把节点都放进数组然后在建立联系。

Node* treeToDoublyList(Node* root) {
    
    
        if (!root) return NULL;
        vector<Node*> nodelist;
        inorder(nodelist, root);
        int l = nodelist.size();
        if (l == 1)
        {
    
    
            nodelist[0]->right = nodelist[0];
            nodelist[0]->left = nodelist[0];
            return nodelist[0];
        }
        for (int i = 1; i < l - 1; i++) {
    
    
            nodelist[i]->left = nodelist[i - 1];
            nodelist[i]->right = nodelist[i + 1];
        }
        nodelist[0]->left = nodelist[l - 1];
        nodelist[0]->right = nodelist[1];
        nodelist[l - 1]->right = nodelist[0];
        nodelist[l - 1]->left = nodelist[l - 2];
        return nodelist[0];
    }
    void inorder(vector<Node*>& nodelist, Node* root)
    {
    
    
        if (root == NULL)return;
        inorder(nodelist, root->left);
        nodelist.push_back(root);
        inorder(nodelist, root->right);
    }

猜你喜欢

转载自blog.csdn.net/qq_41884662/article/details/115435271