二叉排序树-BST
-
二叉排序树:对于二叉排序树的任何一个非叶子结点,要求左子结点的值比当前结点小,右子结点的值比当前结点的值大。若相同则可以放在左子结点或右子结点。
-
二叉排序树的创建和遍历
插入:
通过与根结点值的比较后,确定往左子树还是右子树去查找,查找直至某个叶子结点的左子树或右子树为空为止,则插入结点应为该叶子结点的左孩子或者右孩子。
插入的元素一定在叶结点上
关键字的输入顺序不同,建立的二叉排序树也不同
/**
* 递归的添加结点
*
* @param node
*/
public void add(Node node) {
if (node == null) {
return;
}
// 判断传入的值与当前子树的根结点值的关系,在其左、右子树上查找
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 class BinarySortTreeDemo {
public static void main(String[] args) {
int[] arr = {
7, 3, 10, 12, 5, 1, 9 };
BinarySortTree bst = new