简介
搜索二叉树:左节点小于根节点,根节点小于右节点。如果对搜索二叉树进行中序遍历的话,那就是一个排好序的数组。
搜索二叉树具有查找快,删除快,添加快,等于综合了顺序存储和链式存储的优点。
搜索二次函数的代码实现
包含了三个方法,添加,删除,查找
Node类
package com.wuxudong.BinarySortTree;
public class Node {
int value;
Node left;
Node right;
public Node(int value){
this.value=value;
}
//添加方法
public void add(Node node){
//判断当前节点和传入的节点的大小
if(node.value<this.value){
if (this.left==null){
this.left=node;
}else {
this.left.add(node);
}
}else {
if (this.right==null){
this.right=node;
}
else {
this.right.add(node);
}
}
}
public void midShow(Node node){
if (node==null){
return;
}
midShow(node.left);
System.out.println(node.value);
midShow(node.right);
}
public void midShow() {
Node root=this;
midShow(root);
}
public Node search(int value) {
//获取当前节点
Node node=this;
if (this.value==value){
return node;
}else if (this.value<value){
return node.right.search(value);
}else {
return node.left.search(value);
}
}
public Node findParent(Node node) {
if ((this.left!=null&&this.left.value==node.value)||(this.right!=null&&this.right.value==node.value)){
return this;
}else if (this.value>node.value){
return this.left.findParent(node);
}else if (this.value<node.value){
return this.right.findParent(node);
}else {
return null;
}
}
@Override
public String toString() {
return "Node{" +
"value=" + value +
'}';
}
}
BinaryTree类
package com.wuxudong.BinarySortTree;
public class BinarySortTree {
Node root;
//添加节点
public void add(Node node){
if (root==null){
root=node;
}else {
root.add(node);
}
}
//中序遍历,即按照已经排好的顺序
public void midShow(){
root.midShow();
}
//查找节点
public Node search(int value){
if (root==null){
return null;
}else {
return root.search(value);
}
}
public void deleteNode(int i) {
if (root==null){
return;
}else {
//找出要删除的节点
Node node=search(i);
//如果找不到这个节点
if (node==null){
return;
}
//找出删除节点的父节点
Node parent = findParent(node);
//如果删除的节点是叶子节点
if (node.left==null&&node.right==null&&parent.left==node){
parent.left=null;
}else if (node.right==null&&node.left==null&&parent.right==node){
parent.right=null;
//如果删除的节点只有一个子节点
//右节点为空
}else if (node.right==null&&node.left!=null){
parent.left=node.left;
//左节点为空
}else if (node.left==null&&node.right!=null){
parent.right=node.right;
}else {
//删除的节点有两个节点
//找出右子树的最小值
int min=findRightMin(node.right);
node.value=min;
}
}
}
public int findRightMin(Node node) {
Node target=node;
while (target.left!=null){
target=target.left;
}
deleteNode(target.value);
return target.value;
}
public Node findParent(Node node) {
if (root==null){
return null;
}else if (root==node){
return root;
}
else{
return root.findParent(node);
}
}
}
测试类
package com.wuxudong.BinarySortTree;
public class TestBinarySortTree {
public static void main(String[] args) {
int [] arr=new int[] {7,3,10,12,5,1,9};
BinarySortTree tree=new BinarySortTree();
for (int i:arr){
tree.add(new Node(i));
}
//System.out.println(tree.root);
//tree.midShow();
//Node node= tree.search(7);
//System.out.println(node.value);
//删除节点
tree.deleteNode(12);
tree.midShow();
}
}