package tree;
public class BinaryTree<Key extends Comparable<Key>, Value> {
private int N;
private Node root;
private class Node {
public Key K;
public Value V;
public Node left;
public Node right;
public Node(Key k, Value v, Node left, Node right) {
K = k;
V = v;
this.left = left;
this.right = right;
}
}
//获取元素个数
public int size() {
return N;
}
//向树中添加元素key-value
public void put(Key key, Value value) {
root = put(root, key, value);
}
public Node put(Node x, Key key, Value value) {
//首先判断进来的树是不是空树,如果是空树,那么该节点为根节点
if (x == null) {
N++;
return new Node(key, value, null, null);
}
//如果传进来的树不是空树,那么我们就要判断大于,小于,等于,这三种情况
if (key.compareTo(x.K) < 0) {
//这种情况是传进来的节点key小于父节点key,所以进入左子树
x.left = put(x.left, key, value);
} else if (key.compareTo(x.K) > 0) {
//这种情况是传进来的节点key大于父节点key,所以进入右子树
x.right = put(x.right, key, value);
} else {
x.V = value;
}
return x;
}
//查询树中指定key对应的value
public Value get(Key key) {
return get(root, key);
}
//从指定的树x中,查找key对应的值
public Value get(Node x, Key key) {
//首先判断进来的树是不是空树,如果是空树,那么返回null
if (x == null) {
return null;
}
if (key.compareTo(x.K) < 0) {
//这种情况是传进来的节点key小于父节点key,所以进入左子树
return get(x.left, key);
} else if (key.compareTo(x.K) > 0) {
//这种情况是传进来的节点key大于父节点key,所以进入右子树
return get(x.right, key);
} else {
return x.V;
}
}
//删除树中key对应的value
public void delete(Key key) {
delete(root, key);
}
//删除指定树x中的key对应的value,并返回删除后的新树
public Node delete(Node x, Key key) {
//首先判断进来的树是不是空树,如果是空树,那么返回null
if (x == null) {
return null;
}
if (key.compareTo(x.K) < 0) {
//这种情况是传进来的节点key小于父节点key,所以进入左子树
x.left = delete(x.left, key);//删除这个节点后,会生成一个新的左子树,返回这个左子树即可
} else if (key.compareTo(x.K) > 0) {
//这种情况是传进来的节点key大于父节点key,所以进入右子树
x.right = delete(x.right, key);
} else {
N--;
//此时完成真正的删除动作,找到能替换删除节点的这个新节点。
if (x.right == null) {
return x.left;
}
if (x.left == null) {
return x.right;
}
Node minNode = x.right;
while (minNode.left != null) {
minNode = minNode.left;
}
//删除最小节点
Node n = x.right;
while (n.left != null) {
if (n.left.left == null) {
n.left = null;
} else {
n = n.left;
}
}
minNode.left = x.left;
minNode.right = x.right;
x = minNode;
}
return x;
}
}
可以对其进行简单测试,如有问题请您留言告诉我,谢谢。
package tree;
public class TestBinaryTree {
public static void main(String[] args) {
BinaryTree<Integer,String> tree=new BinaryTree<>();
tree.put(1,"a");
tree.put(2,"b");
tree.put(3,"c");
tree.put(4,"d");
System.out.println("共几个元素:"+tree.size());
tree.delete(3);
System.out.println("共几个元素:"+tree.size());
System.out.println(tree.get(1));
System.out.println(tree.get(2));
System.out.println(tree.get(3));
System.out.println(tree.get(4));
}
}