1 Star 0 Fork 0

invictusQAQ/BinarySearchTree

加入 Gitee
与超过 1200万 开发者一起发现、参与优秀开源项目,私有仓库也完全免费 :)
免费加入
文件
该仓库未声明开源许可证文件(LICENSE),使用请关注具体项目描述及其代码上游依赖。
克隆/下载
BinarySearchTreeDemo.java 3.23 KB
一键复制 编辑 原始数据 按行查看 历史
invictusQAQ 提交于 2022-07-04 10:15 +08:00 . 二叉搜索树
import java.util.*;
class Node{
public int val;
public Node left;
public Node right;
public Node(int val){
this.val=val;
}
}
public class BinarySearchTreeDemo {
public Node root=null;
public Node Search(int key){
Node cur=root;
while(cur!=null){
if(cur.val<key){
cur=cur.right;
}else if(cur.val==key){
return cur;
}else{
cur=cur.right;
}
}
return null;
}
public boolean insert(int val){
if(root==null){
root=new Node(val);
return true;
}
Node cur=root;
Node parent=null;
while(cur!=null){
if(cur.val<val){
parent = cur;
cur = cur.right;
}else if(cur.val==val){
return false;
}else{
parent=cur;
cur=cur.left;
}
}
Node node=new Node(val);
if(parent.val < val) {
parent.right=node;
}else {
parent.left = node;
}
return true;
}
public void remove(int key){
Node cur=root;
Node parent=null;
while(cur!=null){
if(cur.val==key){
removeNode(cur,parent);
break;
}else if(cur.val<key){
parent=cur;
cur=cur.right;
}else{
parent=cur;
cur=cur.left;
}
}
}
private void removeNode(Node cur,Node parent){
if(cur.left == null){
if(cur==root){
root=cur.right;
}else if(cur==parent.left){
parent.left=cur.right;
}else{
parent.right=cur.right;
}
}else if(cur.right==null){
if(cur==root){
root=cur.left;
}else if(cur==parent.left){
parent.left=cur.left;
}else{
parent.right=cur.left;
}
}else{//如果左右均存在节点,则找到左树最大值或者右树最小值然后交换
Node targetParent = cur;
Node target=cur.right;//右树找最小
while(target.left!=null){
targetParent=target;
target=targetParent.left;
}
cur.val=target.val;//交换
if(target == targetParent.left) {//删除
targetParent.left = target.right;
}else {
targetParent.right = target.right;
}
}
}
public void inOrder(Node root) {
if(root == null) return;
inOrder(root.left);
System.out.print(root.val+" ");
inOrder(root.right);
}
public static void main(String[] args) {
int[] array = {7,2,4,6,3,5,1,8};
BinarySearchTreeDemo binarySearchTree = new BinarySearchTreeDemo();
for (int i = 0; i < array.length; i++) {
binarySearchTree.insert(array[i]);
}
binarySearchTree.inOrder(binarySearchTree.root);
System.out.println();
//binarySearchTree.remove(50);
binarySearchTree.inOrder(binarySearchTree.root);
}
}
Loading...
马建仓 AI 助手
尝试更多
代码解读
代码找茬
代码优化
Java
1
https://gitee.com/invictusQAQ/BinarySearchTree.git
git@gitee.com:invictusQAQ/BinarySearchTree.git
invictusQAQ
BinarySearchTree
BinarySearchTree
master

搜索帮助