数据结构之二叉排序树

二叉排序树(Binary Sort Tree),又称二叉查找树(Binary Search Tree),亦称二叉搜索树。是数据结构中的一类。在一般情况下,查询效率比链表结构要高。

特点:

(1)若左子树不空,则左子树上所有节点的值均小于它的根节点的值;

(2)若右子树不空,则右子树上所有结点的值均大于它的根结点的值;

(3)左、右子树也分别为二叉排序树;

让我们来实现下,首先定义一个节点类,由于测试也不再添加泛型,直接使用int来做二叉搜索树item。

节点类代码:

public class Node{
   private int item;

   private Node leftChild;//左孩子

   private Node rightChild;//右孩子

    public Node(int item, Node leftChild, Node rightChild) {
        this.item = item;
        this.leftChild = leftChild;
        this.rightChild = rightChild;
    }

    public Node() {
    }

    public Node(int item) {
        this.item = item;
    }

    public int getItem() {
        return item;
    }

    public void setItem(int item) {
        this.item = item;
    }

    public Node getLeftChild() {
        return leftChild;
    }

    public void setLeftChild(Node leftChild) {
        this.leftChild = leftChild;
    }

    public Node getRightChild() {
        return rightChild;
    }

    public void setRightChild(Node rightChild) {
        this.rightChild = rightChild;
    }
}

然后来构建一个二叉搜索树

普通循环实现代码如下:

  public static Node getSortTree(int[] arr,Node root){

        for(int i:arr){
            Node node=new Node(i,null,null);
            if(root==null){
                root=node;
            }else{
                    Node newRoot=root;
                    Node parent=null;
                    while(newRoot!=null){
                        parent=newRoot;
                        newRoot=newRoot.getItem()>node.getItem()?newRoot.getLeftChild():newRoot.getRightChild();
                    }

                if (parent.getItem() > node.getItem()) {
                    parent.setLeftChild(node);
                } else {
                    parent.setRightChild(node);
                }
            }
        }

        return root;
    }

然后是遍历二叉搜索树(中序遍历)代码如下:

//递归
public static void printNode(Node root){
        if(root==null) return;

        printNode(root.getLeftChild());
        System.out.println(root.getItem());
        printNode(root.getRightChild());
    }

//循环
 Stack<Node> stack=new Stack<>();//来保存遍历过左孩子和根节点

        Node newRoot=root;
        while(newRoot!=null || !stack.isEmpty()){

            while(newRoot!=null){
                stack.push(newRoot);
                newRoot=newRoot.getLeftChild();
            }

            if(!stack.isEmpty()){
                newRoot=stack.pop();//访问右节点
                System.out.println(newRoot.getItem());
                newRoot=newRoot.getRightChild();
            }
        }

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

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值