package zcj;
/**
* Created by admin on 2016/4/15.
*/
public class BinarySearchTree {
//定义一个二叉树的节点
private class TreeNode {
public int val;
public TreeNode left;
public TreeNode right;
public TreeNode(int element) {
val = element;
left = null;
right = null;
}
}
//二叉查找树元素的查找
public boolean find(TreeNode head,int x){
if(head==null) return false;
if(head.val==x) return true;
else if(head.val>x) return find(head.left,x);
else return find(head.right,x);
}
//二叉查找树的元素的插入
public TreeNode insert(TreeNode head,int x){
if(head==null) {
head= new TreeNode(x);
return head;
}
else{
if(head.val==x) return head ;
else if(x<head.val){
head.left=insert(head.left,x);
}
else{
head.right=insert(head.right,x);
}
}
return head;
}
//二叉查找树的最小元素的查找
public TreeNode findMin(TreeNode t){
if(t==null) return null;
if(t.left==null) return t;
else return findMin(t.left);
}
//二叉查找树元素的删除
public TreeNode delete(TreeNode t,int x){
if(t==null) return null;
if(t.val>x){
t.left=delete(t.left,x);
}
else if(t.val<x){
t.right=delete(t.right,x);
}
else if(t.left!=null&&t.right!=null){
TreeNode min=findMin(t.right);
t.val=min.val;
//删除节点min
}
else{
if(t.left!=null)
t=t.left;
else
t=t.right;
}
return t;
}
}
其中:删除某个节点当左右子树都存在时,将右子树的最小值替换当前节点,并删除最小节点,删除代码没写
二叉搜索树的基本java实现
最新推荐文章于 2024-07-31 21:03:53 发布