将二叉搜索树转换为排序的双向链表

本文介绍了一种将二叉搜索树转化为双向链表的方法。通过找到树中的最左侧节点作为链表的头,并按照中序遍历规则修改每个节点的左右孩子指向,实现树到链表的转换。文章提供了详细的步骤说明及代码实现。

步骤:
1.找链表的首节点----就是树中最小的节点---->最小的节点就是树中最左侧节点。
2.按照中序遍历的规则来修改每个节点左右孩子的指向。
分析:每拿到- -个节点—只能修改当前节点的左指针域–原因:因为按照中序规则进行遍历,肯定知道当前节点的前一个节点是那个节点(因为其前一个节点刚刚遍历过),当前节点的后序还没有遍历。

public class BSTree {
    public static class BSTNode{
        BSTNode left = null;
        BSTNode right = null;
        int val;
        BSTNode(int val){
            this.val = val;
        }
    }
    private  BSTNode root = null;
    BSTNode prev = null;//标记中序遍历刚刚遍历过的节点。
    public BSTNode BSTree2DList(){
        if (null == root){
            return null;
        }
        //1.找树中最左侧的节点,即双向链表的头
        BSTNode head = root;
        while (null != head.left){
            head = head.left;
        }
        //2.修改每个节点left和right的指向

        BSTree2DList(root);
        return head;
    }
    public void BSTree2DList(BSTNode root){
        if (null == root){
            return;
        }
        //转化根节点的左子树
        BSTree2DList(root.left);
        //转化根节点
        root.left = prev;
        if (null != prev){
            prev.right = root;
        }
        //用prev将刚刚遍历的节点保存起来。
        prev = root;
        BSTree2DList(root.right);
    }
    public static void TestBSTree2(){
        int[] array = {5,3,4,1,7,8,2,6,0,9};
        BSTree t = new BSTree();
        for (int e:array){
            t.put(e);
        }
        BSTNode head = t.BSTree2DList();
        BSTNode cur = head;
        while (cur!=null){
            System.out.print(cur.val + "----->");
            cur = cur.right;
        }
        System.out.println("NULL");
    }
    public static void main(String[] args) {
        TestBSTree2();
    }
}
/*
打印结果:
0----->1----->2----->3----->4----->5----->6----->7----->8----->9----->NULL
*/
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值