package algorithm.tree;
/**
* The class Bst 二叉查找树
*
* @author: zhangtao
* @since: 2021/06/10 上午1:19
*/
public class Bst {
public static void main(String[] args) {
Node root = insert(null, 5);
insert(root, 1);
insert(root, 2);
insert(root, 3);
insert(root, 4);
insert(root, 5);
insert(root, 6);
insert(root, 7);
insert(root, 8);
insert(root, 9);
insert(root, 10);
insert(root, 11);
insert(root, 12);
ldr(root);
delete(root,5);
delete(root,12);
delete(root,13);
ldr(root);
}
/**
* 二叉查找树的插入
*
* @param root 待插入的树根
* @param data 待插入的节点值
* @return 插入后的树根
*/
private static Node insert(Node root, int data) {
if (root == null) {
//为空树则创建节点并返回节点的指针
root = new Node(data);
return root;
}
if (data < root.data) {
//插入左子树 并刷新插入节点后新的树根指针
root.left = insert(root.left, data);
}
if (data > root.data) {
//插入右子树 并刷新插入节点后新的树根指针
root.right = insert(root.right, data);
}
//返回树根
return root;
}
/**
* 二叉查找树查找节点
*
* @param root 树根
* @param data 待查节点数据
* @return 是否找到
*/
private static boolean search(Node root, int data) {
if (root == null) {
//未找到
System.out.println("未找到:" + data);
return false;
}
if (root.data == data) {
System.out.println("找到了:" + data);
return true;
} else if (data < root.data) {
return search(root.left, data);
} else {
return search(root.right, data);
}
}
/**
* 中根遍历二查找树 输出数据升序排列
*
* @param root 树根
*/
private static void ldr(Node root) {
if (root == null) {
return;
}
ldr(root.left);
System.out.println(root.data);
ldr(root.right);
}
private static Node delete(Node root, int data) {
if (root == null) {
System.out.println("删除失败:" + data);
return null;
}
if (data < root.data) {
root.left = delete(root.left, data);
} else if (data > root.data) {
root.right = delete(root.right, data);
} else {
//找到了
if (root.left == null) {
//左子树为空则直接使用右子树继承
root = root.right;
} else if (root.right == null) {
//左子树继承
root = root.left;
} else {
//左右子树均存在 则默认使用右子树中最小节点继承root节点
root.data = findMinData(root.right);
root.right = deleteMin(root.right);
}
System.out.println("删除成功:" + data);
}
//返回树根
return root;
}
private static int findMinData(Node root) {
while (root.left != null) {
root = root.left;
}
return root.data;
}
/**
* 删除最小节点并返回新树根
*
* @param root
* @return
*/
private static Node deleteMin(Node root) {
if (root.left == null) {
return root.right;
} else {
// 继续查找最左节点
return deleteMin(root.left);
}
}
/**
* 二叉树的复制
*
* @param root
* @return
*/
private static Node copy(Node root) {
if (root == null) {
return null;
}
Node cpt = new Node(root.data);
cpt.left = copy(root.left);
cpt.right = copy(root.right);
return cpt;
}
}