首先定义结点类 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;
}
用Java语言实现二叉树的结点插入
最新推荐文章于 2023-12-18 08:18:40 发布
本文详细介绍了如何使用Java编程语言来实现二叉树的数据结构,并探讨了如何向二叉树中插入新节点的方法,包括节点的创建、比较和插入逻辑。
摘要由CSDN通过智能技术生成