微软面试100题系列---把二叉查找树转换成排序的双向链表

题目:把二叉查找树转换成排序的双向链表

输入:一个二叉查找树

输出:排序的双向链表;​

要求:不能创建任何新的节点,只能调整指针的方向;

实现

思路:对二叉查找树进行中序遍历,对遍历的当前节点加入到链表末尾即可;加入链表的head和tail,当前的节点curr:

curr->next=null;curr->pre=tail;tail->next=curr;tail=curr;

实现代码:

public class Num1 {
    public static BSTreeNode head=null;
    public static BSTreeNode tail=null;

    /*
     * insert search tree to double link
     */
    public static void main(String[] args) {
        //create a search tree to test
        BSTreeNode root=null;
        root=addBSTreeNode(root,10);
        addBSTreeNode(root,6);
        addBSTreeNode(root,14);
        addBSTreeNode(root,4);
        addBSTreeNode(root,8);
        addBSTreeNode(root,12);
        addBSTreeNode(root,16);

        inOrderBSTree(root);

        //print result
        BSTreeNode node=head;
        while(node.right!=null){
            System.out.print(node.value+" ");
            node=node.right;
        }

    }
    public static BSTreeNode addBSTreeNode(BSTreeNode root,int value){
        BSTreeNode node=new BSTreeNode(value,null,null);
        if(root==null){
            root=node;
            return root;
        }
        BSTreeNode curr=root;
        BSTreeNode parent=null;

        while(curr!=null){
            parent=curr;
            if(curr.value<value){
                curr=curr.right;
            }else{
                curr=curr.left;
            }
        }

        //insert node to parent's child
        if(parent.value<value){
            parent.right=node;
        }else{
            parent.left=node;
        }

        return root;
    }

    public static void inOrderBSTree(BSTreeNode root){
        if(root==null){
            return;
        }
        if(root.left!=null){
            inOrderBSTree(root.left);
        }
        //System.out.println(root.value);
        convertIntoDoubleList(root);

        if(root.right!=null){
            inOrderBSTree(root.right);
        }
    }

    private static void convertIntoDoubleList(BSTreeNode node) {
        node.left=tail;
        if(tail==null){
            head=node;
        }else{
            tail.right=node;
        }
        tail=node;      
    }

}
class BSTreeNode{
     int value;
     BSTreeNode left;
     BSTreeNode right;

    public BSTreeNode(int value,BSTreeNode left,BSTreeNode right){
        this.value=value;
        this.left=left;
        this.right=right;
    }
    public BSTreeNode(int value){
        this(value,null,null);
    }
}

​​

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值