二叉排序树
package tree;
/**
* 实现二叉排序树
* @author User
*
*/
public class BinarySortTree {
Node root;
/**
* 往二叉排序树中加入元素
* @param data
*/
public void add(int data) {
Node node = new Node(data);
Node temp = root;
if(root == null) {
root = node;
}else {
while(true) {
// 如果严格小于就往左边放
if(data < temp.data) {
if(temp.left == null) {
temp.left = node;
return;
}else {
// 如果左边节点不为空,就将左边的节点变成当前节点,然后继续循环找
temp = temp.left;
}
}
// 否则也就是大于等于就往右边放
else {
if(temp.right == null) {
temp.right = node;
return;
}else {
temp = temp.right;
}
}
}
}
}
/**
* 中序遍历
* @param node
*/
public void middleShow(Node node) {
if(node == null) {
return;
}
middleShow(node.left);
System.out.print(node.data + " ");
middleShow(node.right);
}
/**
* 前序遍历
* @param node
*/
public void frontShow(Node node) {
if(node == null) {
return;
}
System.out.print(node.data + " ");
frontShow(node.left);
frontShow(node.right);
}
/**
* 后序遍历
* @param node
*/
public void backShow(Node node) {
if(node == null) {
return;
}
backShow(node.left);
backShow(node.right);
System.out.print(node.data + " ");
}
}
class Node{
int data;
Node left;
Node right;
public Node(int data) {
this.data = data;
}
}
测试类
package tree;
public class Test {
public static void main(String[] args) {
int[] arr = new int[] {2,8,7,4,9,3,1,6,10,5};
BinarySortTree tree = new BinarySortTree();
for(int i : arr) {
tree.add(i);
}
tree.middleShow(tree.root);
System.out.println("======================");
tree.frontShow(tree.root);
System.out.println("======================");
tree.backShow(tree.root);
}
}
运行结果