用Java语言实现二叉树的结点插入

时间:2021-09-15 12:29:08
首先定义结点类   class  Node:

public class Node {
public Integer value =null;
public Node leftchild=null;
public Node rightchild =null;
public Node parent=null;

}



然后定义二叉树类 class Btree:

public class Btree {

private Node root = null;

// 在二叉树中插入一个数
public void insert(Integer val) {
Node p = new Node();
p.value = val;

//如果二叉树为空,直接将要插入的值作为根
if (this.root == null) {
this.root = p;
}

//如果二叉树不为空,判断要插入的数与此时p所指结点的值的大小,如果插入的数大,那么就插到右孩子,反之插入到左孩子。
else {
Node q = this.root;
while (true) {

if (val < q.value) {
if (q.leftchild == null) {

//双向指向
q.leftchild = p;
p.parent=q;
break;
}
else {
q = q.leftchild;
}
}
else if (val > q.value) {
if (q.rightchild == null) {

//双向指向
q.rightchild = p;
p.parent=q;
break;
}
else {
q = q.rightchild;
}

}
else {
System.out.println("已存在");
}
}
}
}


最后定义主函数 class Main :

public class Main {

public static void main(String[] args) {
Btree b =new Btree();
Integer[] data={3,2,5,4,8,7,9};
for(Integer i=0;i<data.length;i++){
b.insert(data[i]);
}
}