1、二叉树
二叉排序树:从任意节点开始,节点左侧节点值总比节点右侧值要小。
一个详细讲解的博客: https://www.cnblogs.com/bigsai/p/11382172.html
二叉查找树:根节点的值大于其左子树中任意一个节点的值,小于其右节点中任意一节点的值,这一规则适用于二叉查找树中的每一个节点。
二叉搜索树:每个父节点都有两个子节点(子节点可能为空),左子节点比父节点小,右子节点比父节点大。
C++实现: https://www.cnblogs.com/mcomco/p/10184033.html
一些习题:https://www.cnblogs.com/nonlinearthink/p/11042714.html
2、二叉排序树的java实现
{7,3,10,12,5,1,9}构建的二叉排序树为:
//实现binarysorttree;
public class BstDemo {
public static void main(String[] args) {
int[] arr = {7,3,10,12,5,1,9};
BinarySortTree binarysorttree = new BinarySortTree();
for(int i=0;i<arr.length;i++) { //通过循环添加数组节点
binarysorttree.add(new Node(arr[i]));
}
binarysorttree.perOrder();
}
}
//二叉排序树创建
class BinarySortTree{
private Node root;
//添加节点的方法
public void add(Node node) {
if(root == null) {
root = node;
}else {
root.add(node);
}
}
//前序遍历
public void perOrder() {
if(root == null) {
System.out.println("二叉树是空树,不能遍历");
}else {
root.preOrder();
}
}
}
//节点
class Node{
int value;
Node left;
Node right;
public Node(int value) {
this.value = value;
}
@Override
public String toString() {
return "Node [value=" + value + "]";
}
//添加节点的方法
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 void preOrder() {
System.out.println(this.toString());
if(this.left != null) {
this.left.preOrder();
}
if(this.right != null) {
this.right.preOrder();
}
}
}
前序遍历执行结果
Node [value=7]
Node [value=3]
Node [value=1]
Node [value=5]
Node [value=10]
Node [value=9]
Node [value=12]