1.何为二叉查找树?
(1)若左子树不空,则左子树上所有结点的值均小于它的根结点的值;
(2)若右子树不空,则右子树上所有结点的值均大于它的根结点的值;
(3)左、右子树也分别为二叉排序树;
(4)没有键值相等的结点。
2.二叉查找树的简单实现:
package com.hmi.test;
public class BinarySearchTree {
int data; // 数据
BinarySearchTree left; // 左二叉树
BinarySearchTree right;// 右二叉树
public BinarySearchTree(int data) {
this.data = data;
left = null;
right = null;
}
/**
* 插入元素
* @param root 根节点元素
* @param data 要插入的数据
*/
public void insert(BinarySearchTree root, int data) {
if (root.data > data) {
if (root.left != null) {
insert(root.left, data);
}
if (root.left == null) {
root.left = new BinarySearchTree(data);
}
} else if (root.data < data) {
if (root.right != null) {
insert(root.right, data);
}
if (root.right == null) {
root.right = new BinarySearchTree(data);
}
}
}
/**
* 前序遍历
* @param root 根节点元素
*/
public void preOrder(BinarySearchTree root) {
if (root != null) {
System.out.print(root.data + " ");
preOrder(root.left);
preOrder(root.right);
}
}
/**
* 中序遍历
* @param root 根节点元素
*
*/
public void inOrder(BinarySearchTree root) {
if (root != null) {
inOrder(root.left);
System.out.print(root.data + " ");
inOrder(root.right);
}
}
/**
* 后序遍历
* @param root 根节点元素
*/
public void postOrder(BinarySearchTree root) {
if (root != null) {
postOrder(root.left);
postOrder(root.right);
System.out.print(root.data + " ");
}
}
public static void main(String[] args) {
int []data = {34,16,45,24,10,56,36};
BinarySearchTree root = new BinarySearchTree(data[0]);
//循环插入二叉树
for (int i = 1; i < data.length; i++) {
root.insert(root, data[i]);
}
System.out.println("前序遍历为:");
root.preOrder(root);
System.out.println();
System.out.println("中序遍历为:");
root.inOrder(root);
System.out.println();
System.out.println("后序遍历为:");
root.postOrder(root);
}
}
运行结果:
数据就没用节点了,直接用的整型数据,二叉查找树数据的插入及遍历主要就是运用了递归的思想。