二叉搜索树转有序双向链表

题目描述:

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

 

 

解题方法:

由于二叉搜索树的中序遍历,按照由小到大的顺序依次遍历树中的每个结点,所以可以利用中序遍历解决此题。

使用指针last指向上一次遍历的结点,将last指向的结点与本次遍历的结点互连。

 

新建一个结点head,last初始指向head;

中序遍历的第一个结点是结点4,将last与结点4互连, 也即head与结点4互连,同时将last指向结点4;

中序遍历的第二个结点是结点6,将last与结点6互连, 也即结点4与结点6互连,同时将last指向结点6;

。。。

最后断开head与结点4的链接,返回结点4.

 

 

 实现代码:

    // 新建一个结点,作为整个链表的起始点
    private static TreeNode head = new TreeNode(0);
    // 指向上个结点,初始指向head结点
    private static TreeNode last = head;

    // 利用中序遍历构建双向链表
    private static void convert(TreeNode node) {
        if (node == null) return;

        convert(node.left);
        // 将上个结点与该结点互连
        last.right = node;
        node.left = last;
        last = node;

        convert(node.right);
    }

    public static TreeNode BST2BiList(TreeNode root) {
        if (root == null) return null;
        convert(root);
        // 与head相连的结点为链表的起始点
        // 断开head与其相连结点的链接,并返回该结点
        last = head.right;
        last.left = null;
        head.right = null;
        return last;
    }

 

posted on 2018-08-14 17:13  Deltadeblog  阅读(385)  评论(0编辑  收藏  举报

导航