剑指offer-27.二叉搜索树与双向链表

https://www.nowcoder.com/practice/947f6eb80d944a84850b0538bf0ec3a5?tpId=13&tqId=11179&tPage=2&rp=1&ru=%2Fta%2Fcoding-interviews&qru=%2Fta%2Fcoding-interviews%2Fquestion-ranking

题目描述
输入一棵二叉搜索树,将该二叉搜索树转换成一个排序的双向链表。要求不能创建任何新的结点,只能调整树中结点指针的指向。

这里写图片描述

题解:

中序遍历二叉树的顺序即为生成的双向链表的结点顺序。

用 head 指向双向链表头,tail 指向当前链表的尾。

按中序遍历不断在双向链表尾加入结点。

当我们遍历转换到根结点10时,它的左子树已经转换成一个排序的链表了,tai指向的是左子树最大的结点8,我们把8和10连接起来,再把tail 指向 10。接着去遍历转换右子树。

这里写图片描述

class Solution {
    TreeNode head = null;// 双向链表的头
    TreeNode tail = null;// 双向链表的尾,不断移动

    public TreeNode Convert(TreeNode pRootOfTree) {
        if (pRootOfTree == null) {
            return null;
        }
        ConvertNode(pRootOfTree);
        return head;
    }

    private void ConvertNode(TreeNode pCurrent) {
        if (pCurrent == null) {
            return;
        }

        ConvertNode(pCurrent.left);

        // 中序遍历第一个访问到的元素,即最小的元素,即双向链表的头,此时尾结点也指向他
        if (head == null) {
            head = pCurrent;
            tail = pCurrent;
        } else {//当前根结点插入到左子树生成的链表的尾端,tail向后移动
            pCurrent.left = tail;
            tail.right = pCurrent;
            tail = pCurrent;
        }

        ConvertNode(pCurrent.right);
    }
}

猜你喜欢

转载自blog.csdn.net/zxm1306192988/article/details/81051256