自定义一个简单的二叉树

首先创建一个节点的类,实现Comparable<T>接口

public class Node implements Comparable<Node> {
    public  Object data;
    public  Node  left;
    public  Node right;
    public Node(Object d) {
        this.data = d;
    }

    @Override
    public int compareTo(Node o) {
        return (Integer) this.data-(Integer)o.data;
    }
}

自定义一个二叉树的类,包含contians方法和insert方法

public class BInarySearchTree<T extends Comparable<T>> {
    public Node root;
    public  boolean contains(T i){
      if (root==null){
         return  false;
      }
      Node current =root;
      while (true){
          if (current==null){
             return  false;
          }
         if (i.compareTo((T)current.data)==0){
             return true;
          }else if(i.compareTo((T) current.data) < 0){
             current = current.left;
         }else {
             current = current.right;
          }
      }
    }
    public boolean insert(T i) {
        if (root == null) {
            root = new Node(i);
            return true;
        }

        Node current = root;
        while (true) {
            // 如果 i 比当前结点的值小
            if (i.compareTo((T) current.data) < 0) {
                if (current.left != null) {
                    current = current.left;
                } else {
                    current.left = new Node(i);
                    break;
                }
            } else {
                if (current.right != null)
                    current = current.right;
                else {
                    current.right = new Node(i);
                    break;
                }
            }
        }
        return true;
    }
}

定义一个测试类进行测试

public class Test {
    public static void main(String[] args) {
        BInarySearchTree<Node> bst=new BInarySearchTree<>();
        Node a1=new Node(1);
        Node a2=new Node(5);
        Node a3=new Node(7);
        Node a4=new Node(2);
        Node a5=new Node(3);
        bst.insert(a1);
        bst.insert(a2);
        bst.insert(a3);
        bst.insert(a4);
        bst.insert(a5);
        System.out.println(bst.contains(new Node(5)));
    }
}


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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值