1,定义
二叉搜索树(二叉排序树)或者是一棵空树,或者是具有下列性质的二叉树:
(1)若左子树不空,则左子树上所有结点的值均小于它的根结点的值;
(2)若右子树不空,则右子树上所有结点的值均大于它的根结点的值;
(3)左、右子树也分别为二叉排序树;
(4)没有键值相等的节点。
2,查找
若根结点的关键字值等于查找的关键字,成功。
否则,若小于根结点的关键字值,递归查左子树。
若大于根结点的关键字值,递归查右子树。
若子树为空,查找不成功。
public static boolean find(treeNode node,int value){
if (node == null){
return false;
}
if (node.data == value) {
return true;
} else if (node.data < value) {
return find(node.rightNode, value);
} else
return find(node.leftNode, value);
}
3,删除
(1)若要删除的节点时叶子节点,则将其父节点的指针指向null。
(2)要删除的节点只有一个孩子结点时,则将其父亲节点的指针指向要删除节点的孩子节点。
(3)要删除的节点有左右两颗子树,则用另一节点替换被删除节点:左子树的最大元素或右子树的最小元素。
4,获取高度
public static int get_depth(treeNode node){
if(node == null){
return 0;
}else {
int left_depth = get_depth(node.leftNode);
int right_Depth = get_depth(node.rightNode);
return left_depth>right_Depth?left_depth+1:right_Depth+1;
}
}
5,获取最大元素
public static int get_max(treeNode node){
if (node == null){
return -1;
}else{
int left_max = get_max(node.leftNode);
int right_max = get_max(node.rightNode);
int mid_max = node.data;
int max = mid_max;
if (left_max>max){max = left_max;}
if (right_max>max){max = right_max;}
return max;
}
}
6,前中后序遍历
//前序遍历
public static void preOrder(treeNode node){
if (node != null) {
System.out.print(node.data+" ");
preOrder(node.leftNode);
preOrder(node.rightNode);
}
}
//中序遍历
public static void midorder(treeNode node){
if (node != null){
midorder(node.leftNode);
System.out.print(node.data+" ");
midorder(node.rightNode);
}
}
//后序遍历
public static void postorder(treeNode node){
if (node != null){
postorder(node.leftNode);
postorder(node.rightNode);
System.out.print(node.data+" ");
}
}