二叉树的添加/删除/查找
public class BinaryTree {
public static Node insert(Node root, int k) {
if (root == null) {
return new Node(k);
}
if(k<root.val){
root.l = insert(root.l,k);
}else{
root.r = insert(root.r,k);
}
return root;
}
public static Node search(Node root,int k){
if(root==null||root.val==k){
return root;
}
if(k<root.val){
return search(root.l,k);
}
return search(root.r,k);
}
public static Node delete(Node root,int k){
if(root==null)
return null;
if(k<root.val){
root.l = delete(root.l,k);
}else if(k>root.val){
root.r = delete(root.r,k);
}else{
if(root.l==null)
return root.r;
if(root.r==null)
return root.l;
Node temp = root.r; // 取右节点的最左子节点进行替代
while(temp.l!=null)
temp = temp.l;
root.val = temp.val;
root.r = delete(root.r,root.val);
}
return root;
}
public static void main(String[] args) {
Node node = new Node(5);
insert(node,1);
insert(node,2);
insert(node,3);
insert(node,6);
insert(node,7);
insert(node,8);
System.out.println(node);
delete(node,6);
System.out.println(node);
}
}
class Node {
int val;
Node l = null;
Node r = null;
Node() {
}
Node(int k) {
val = k;
}
@Override
public String toString() {
return "{" +
"'val':" + val +
",'l':" + l +
",'r':" + r +
'}';
}
}