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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值