当前位置:主页 > 查看内容

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

发布时间:2021-04-26 00:00| 位朋友查看

简介:本文解法基于性质二叉搜索树的中序遍历为 递增序列 。 将 二叉搜索树 转换成一个 “排序的循环双向链表” 其中包含三个要素 1.排序链表 节点应从小到大排序因此应使用 中序遍历 2.“从小到大”访问树的节点。 双向链表 在构建相邻节点的引用关系时设前驱节点……

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

将 二叉搜索树 转换成一个 “排序的循环双向链表” ,其中包含三个要素:
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);
    }
;原文链接:https://blog.csdn.net/qq_41884662/article/details/115435271
本站部分内容转载于网络,版权归原作者所有,转载之目的在于传播更多优秀技术内容,如有侵权请联系QQ/微信:153890879删除,谢谢!
上一篇:WireShark实战笔记之TCP三次握手 下一篇:没有了

推荐图文


随机推荐