package test;
import java.util.Scanner;
class Node
{
public int num;
public Node left;
public Node right;
Node(int i)
{
this.num=i;
left = null;
right = null;
}
}
public class Tree {
private static Node root;
public static void main(String[] args) {
// TODO Auto-generated method stub
Scanner sc = new Scanner(System.in);
int n = sc.nextInt();//输入节点个数
int[] a = new int[n];
for(int i = 0;i<n;i++)
{
a[i]=sc.nextInt();
}
root = new Node(a[0]);//创建根节点
createTree(a);//创建二叉排序树
InOrderTraverse(root);//中序遍历
int num = sc.nextInt();
search(root, num);
InOrderTraverse(root);
}
/*创建节点*/
public static Node createNode(int a)
{
Node node = new Node(a);
return node;
}
/*创建二叉排序树*/
public static void createTree(int[] a)
{
for(int i=1;i<a.length;i++)
{
insert(root, createNode(a[i]));
}
System.out.println("success!");
}
/*节点插入*/
public static void insert(Node root,Node node)
{
if(root.num>node.num)
{
if(root.left==null)
root.left=node;
else
insert(root.left, node);
}else if(root.num<node.num)
{
if(root.right==null)
root.right=node;
else
insert(root.right,node);
}else
return;
}
/*中序遍历*/
public static void InOrderTraverse (Node root)
{
if(root!=null)
{
InOrderTraverse(root.left);
System.out.print(root.num+" ");
InOrderTraverse(root.right);
}
}
/*查找*/
public static void search(Node node,int num)
{
if(node!=null)
{
if(node.num==num)
{
System.out.println("查找成功");
return;
}else if(node.num>num)
{
search(node.left,num);
}else
{
search(node.right, num);
}
}
else
{
System.out.println("不存在"+num+"现在进行插入...");
insert(root, createNode(num));
}
}
}
JAVA数据结构之二叉排序树
最新推荐文章于 2022-12-10 16:16:28 发布