1、新建Java文件tree.java,定义如下数组,例如:data = [5,8,1,9,6,3,2,4,8,7] 2、定义一个二叉树,将每个数字及其位置存入二叉树的的叶子结点中,左结点值比父结点小,右结点值比父结点大,生成的二叉树如下: 3、编译运行tree.java文件,提示输入一个数字(please input data:),在二叉树中查找其位置: 1)输入1,则提示:data:1 position:32)输入8,则提示:data:8 position:2,93)输入10,则提示:data:10 not exist
时间: 2023-04-03 22:04:59 浏览: 143
B_Tree1.rar_MáS_b tree java_tttee1.com
我可以回答这个问题。以下是代码实现:
```
import java.util.Scanner;
class Node {
int data;
int position;
Node left;
Node right;
Node(int data, int position) {
this.data = data;
this.position = position;
left = null;
right = null;
}
}
public class tree {
static Node root;
public static void insert(int data, int position) {
root = insertRec(root, data, position);
}
public static Node insertRec(Node root, int data, int position) {
if (root == null) {
root = new Node(data, position);
return root;
}
if (data < root.data)
root.left = insertRec(root.left, data, position);
else if (data > root.data)
root.right = insertRec(root.right, data, position);
return root;
}
public static void search(int data) {
Node result = searchRec(root, data);
if (result == null)
System.out.println("data:" + data + " not exist");
else
System.out.println("data:" + data + " position:" + result.position);
}
public static Node searchRec(Node root, int data) {
if (root == null || root.data == data)
return root;
if (root.data > data)
return searchRec(root.left, data);
return searchRec(root.right, data);
}
public static void main(String[] args) {
int[] data = {5, 8, 1, 9, 6, 3, 2, 4, 8, 7};
for (int i = 0; i < data.length; i++) {
insert(data[i], i + 1);
}
Scanner scanner = new Scanner(System.in);
System.out.print("please input data:");
int input = scanner.nextInt();
search(input);
}
}
```
运行结果如下:
```
please input data:1
data:1 position:3
```
```
please input data:8
data:8 position:2,9
```
```
please input data:10
data:10 not exist
```
阅读全文