//二叉树节点的创建
class BSTNode <T extends Comparable<T>>{
private T data; // 数据域
private BSTNode<T> left; // 左孩子域
private BSTNode<T> right; // 右孩子域
public BSTNode(T data, BSTNode<T> left, BSTNode<T> right) {
this.data = data;
this.left = left;
this.right = right;
}
public T getData() {
return data;
}
public void setData(T data) {
this.data = data;
}
public BSTNode<T> getLeft() {
return left;
}
public void setLeft(BSTNode<T> left) {
this.left = left;
}
public BSTNode<T> getRight() {
return right;
}
public void setRight(BSTNode<T> right) {
this.right = right;
}
}
树的实现
/**
* BST树的实现
* @param <T>
*/
class BST<T extends Comparable<T>>{
private BSTNode<T> root; // 指向根节点
/**
* BST树的初始化
*/
public BST() {
this.root = null;
}
/**
* BST树的非递归插入操作
* @param data
*/
public void insert(T data){
// 1.判断如果root是null,如果root是null,直接生成根节点,让root指向,结束
if (this.root == null){
this.root = new BSTNode(data,null,null);;
return;
}
// 2.如果root不为空,从根节点开始搜索一个合适的位置,放新节点
BSTNode<T> cur = this.root;
BSTNode<T> parent = null;
while (cur != null){//2、不为空
if (cur.getData().compareTo(data) > 0){
parent = cur;
cur = cur.getLeft();
}
else if(cur.getData().compareTo(data) < 0) {
parent = cur;
cur = cur.getRight();
}else {
return ;
}
}
// 3.生成新节点,把节点的地址,写入父节点相应的地址域
BSTNode node = new BSTNode(data,null,null);
if (parent.getData().compareTo(data) > 0){
parent.setLeft(node);
}else {
parent.setRight(node);
}
}
/**
* 二叉树添加数据(递归)
* @param data
*/
public void inserter(T data){
inserter(root,data);
}
private void inserter(BSTNode<T> root, T data) {
if (root == null){
this.root = new BSTNode<>(data,null,null);
}else {
if (root.getData().compareTo(data) < 0){
if (root.getRight()!= null){
inserter(root.getRight(),data);
}else {
root.setRight(new BSTNode<>(data,null,null));
}
}else {
if (root.getLeft()!=null){
inserter(root.getLeft(),data);
}else {
root.setLeft(new BSTNode<>(data,null,null));
}
}
}
}
}