二叉树是一种能够将链表插入的灵活性和有序数组查找的高效性结合起来的数据结构实现,这个数据结构主要是由一些节点构成。
//
节点包含的链接可以为NULL或者指向其他节点,在二叉树中,每个节点最多只能有一个父节点,而且每个节点都有左右两个子节点,如果把节点指向的位置看成另一颗二叉树,则一个根节点指向的就是它的左右子树。
节点的定义为一个键,一个值,两个左右子节点
public calss Node
{
public :
int key;
int value;
Node *left;
Node *right;
Node(int key,int value)
{
this.key=key;
this.value=value;
}
};
二叉树的定义和方法的定义
public class BST
{
private:
Node root;
public:
int compareto(int x)
{
if(this.key==x)
return 0;
else if(this.key>x)
return 1;
else if(this.key<x)
return -1;
}
int get(Node x,int key)
{
if(root==null)
return null;
int cmp=x.compare(key);//比较键值
if(cmp<0)return get(x.right,key);//如果大于当前节点,则在右子树中查找
else if(cmp>0) return get(x.left,key);//如果小于当前节点,则在左子树中查找
else return x.value;
}
void put(int key,int value)
{
this.root=puthelp(root,key,value);//返回插入节点之后的子树
}
Node puthelp(Node x,int key,int value)
{
if(x==null) return new Node(key,value);//如果为空就新建一个节点
int cmp=x.compareto(key);
if(cmp<0) x.right=puthelp(x.right,key,value);
else if(cmp>0)x.left=puthelp(x.left,key,value);
else
x.value=value;
return x;
}
int min()
{
return minhelp(root).key;//找出键值最小的节点
}
Node minhelp(Node x)
{
if(x.left==null) return x;//如果没有左子树,说明该节点是键值最小
else
return minhelp(x.left);
}
int floor(int key)
{
Node x=floorhelp(root,key);
if(x==null) return null;
return x.key;
}
Node floorhelp(Node x,int key)//找出小于等于key的最大键
{
if(x==null) return null;
int cmp=x.compareto(key);
if(cmp==0)return x;//找到等于key的节点直接放回
if(cmp>0) return floorhelp(x.left,key);//如果当前点大于key,则那个键一定在这个节点的左子树中
Node t=floorhelp(x.right,key);
if(t!=null) return t;
else
return x;
}
void deleteMin()//删除树中最小元素,删除最大元素只需要交换一下左右子树即可
{
root=deletMinhelp(root);
}
Node deletMinhelp(Node x)
{
if(x.left==null) return x.right;//左子树为空,返回右子树,当前节点被排除在树之外
x.left=deleteMinhelp(x.left);
return x;
}
void delete(int key)
{
root=deletehelp(root,key);
}
Node deletehelp(Node x,int key)
{
if(x==null) return;
int cmp=x.compareto(key);
if(cmp>0) x.left=deletehlep(x.left,key);
else if(cmp<0)x.right=deletehelp(x.right,key);
else
{
if(x.right==null) return x.left;
if(x.left==null) return x.right;
Node t=x;
x=min(t.right);//找出右子树最大值或者找出左子树最大值。
x.right=deleteMin(t.right);//删除右子树最小节点。
x.left=t.left;//给左子树赋值
return x;
}
}