问题描述:
构建一个二叉排序树。
知识点:二叉排序树或者是一棵空树,或者具有如下性质:
(1)若它的左子树不空,则左子树上所有节点的值均小于根节点的值;
(2)若它的右子树不空,则右子树上所有节点的值均大于根节点的值;
(3)它的左右子树也分别为二叉排序树。
算法实现:
class Node {
public int value;
public Node left;
public Node right;
public Node(int value) {
this.value = value;
}
@Override
public String toString() {
return "Node [value = " + value + " ]" ;
}
public void addNode(Node node) {
if (node == null) {
return;
}
if (node.value < this.value) {
if (this.left == null) {
this.left = node;
} else {
this.left.addNode(node);
}
} else {
if (this.right == null) {
this.right = node;
} else {
this.right.addNode(node);
}
}
}
}
//创建二叉排序树
class BinarySortTree {
private Node root;
public void add(Node node) {
if(root == null) {
root = node;
} else {
root.addNode(node);
}
}
public Node getRoot() {
return root;
}
}
算法分析:
1.构建节点,并在节点类中实现"增加新节点"到二叉排序树中方法;
2.通过节点类,实现构建二叉排序树的类,并提供返回二叉排序树头结点的方法。
原文:https://www.cnblogs.com/heibingtai/p/12699155.html