算法面试题01:将一棵二元查找树转换成一个排序的双向链表

算法面试题01:将一棵二元查找树转换成一个排序的双向链表(Java实现)

主要考察的内容:

  • 二元查找树的定义
  • 树的三种遍历方式:前序、中序、后序
  • 递归

解题思路:

根据二元查找树的定义: 它首先要是一棵二元树,在这基础上它或者是一棵空树;或者是具有下列性质的二元树:
(1)若左子树不空,则左子树上所有结点的值均小于它的父结点的值;
(2)若右子树不空,则右子树上所有结点的值均大于它的根结点的值;
(3)左、右子树也分别为二元查找树
所以可以判断采用中序遍历二元查找树得到的就是我们需要的目标节点顺序,这里我直接使用了Java Util包中的LinkedList(双向链表),在遍历过程中生成双向链表。

实现代码:

public class BSTreeNode {
    Integer theElement;
    BSTreeNode leftNode;
    BSTreeNode rightNode;

    public BSTreeNode() {
        this(null, null, null);
    }

    public BSTreeNode(Integer theElement) {
        this(theElement, null, null);
    }

    public BSTreeNode(Integer theElement, BSTreeNode leftNode,
            BSTreeNode rightNode) {
        this.theElement = theElement;
        this.leftNode = leftNode;
        this.rightNode = rightNode;
    }

    public BSTreeNode insert(Integer theElement) {
        if (this.theElement == null) {
            this.theElement = theElement;
        } else if (this.theElement > theElement) {
            if (leftNode == null)
                leftNode = new BSTreeNode(theElement);
            else
                leftNode.insert(theElement);
        } else if (this.theElement < theElement) {
            if (rightNode == null)
                rightNode = new BSTreeNode(theElement);
            else
                rightNode.insert(theElement);
        }
        return this;
    }

    public List<Integer> bsTree2LinkedList() {
        List<Integer> result = new LinkedList<Integer>();
        if (this.theElement == null) {
            return result;
        }

        if (this.leftNode != null) {
            result.addAll(leftNode.bsTree2LinkedList());
        }

        result.add(this.theElement);

        if (this.rightNode != null) {
            result.addAll(rightNode.bsTree2LinkedList());
        }
        return result;
    }

    public static void main(String[] args) {
        BSTreeNode bstree = new BSTreeNode();
        bstree = bstree.insert(10).insert(6).insert(14).insert(16).insert(12)
                .insert(4).insert(8);
        List<Integer> result = bstree.bsTree2LinkedList();
        for (Integer i : result) {
            System.out.print(i + " ");
        }
    }
}
  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值