public class MyBinarySearchTree {
public Node root; //记录根节点
public Node current;
class Node{
public Node left; //左孩子
public Node right; //右孩子
public int data; //数据
public Node(int data){
this.left = null;
this.right = null;
this.data = data;
}
}
//增加节点
public void addNode(int data){
if(root == null){ //为空树
root =new Node(data);
}
else{
current = root;
while(current != null){ //寻找叶子节点
if(data <= current.data){
if(current.left == null){
current.left = new Node(data);
break;
}
current = current.left;
}
else{
if(current.right == null){
current.right = new Node(data);
break;
}
current = current.right;
}
}
}
}
//中序遍历树
public void inOrderPrintTree(Node node){
if(node != null){
inOrderPrintTree(node.left);
System.out.print(node.data+",");
inOrderPrintTree(node.right);
}
}
//===========================================================================
public static void main(String[] args) {
MyBinarySearchTree my =new MyBinarySearchTree();
//下列插入顺序可以打乱
my.addNode(9);
my.addNode(5);
my.addNode(15);
my.addNode(3);
my.addNode(7);
my.addNode(11);
my.addNode(17);
my.addNode(6);
my.addNode(4);
my.addNode(1);
my.addNode(10);
my.addNode(8);
my.addNode(12);
my.addNode(16);
my.addNode(7);
System.out.println("中序遍历:");
my.inOrderPrintTree(my.root);
}
}
创建二叉搜索树
最新推荐文章于 2024-05-16 10:30:00 发布