问:使用链表实现二叉树的程序

2025年3月17日 | 阅读 10 分钟

说明

在此程序中,我们需要通过插入节点和以中序方式显示节点来创建二叉树。典型的二叉树可以表示如下

Program to implement Binary Tree using the linked list

在二叉树中,每个节点最多可以有两个子节点。每个节点可以有零个、一个或两个子节点。二叉树中的每个节点包含以下信息

Program to implement Binary Tree using the linked list

Data 表示存储在节点中的值。

Left 表示指向左子节点的指针。

Right 表示指向右子节点的指针。

算法

  1. 定义 Node 类,它有三个属性:data、leftright。其中,left 表示节点的左子节点,right 表示节点的右子节点。
  2. 创建节点时,将数据传递给节点的 data 属性,并将 left 和 right 都设置为 null
  3. 定义另一个类,该类有一个 root 属性。
    1. 表示树的根节点,并将其初始化为 null。
  4. insert() 将向树添加一个新节点
    1. 它检查 root 是否为 null,这意味着树是空的。它将新节点添加为 root。
    2. 否则,它将 root 添加到队列中。
    3. 变量 node 表示当前节点。
    4. 首先,它检查节点是否有左子节点和右子节点。如果有,它将两个节点都添加到队列中。
    5. 如果左子节点不存在,它将新节点添加为左子节点。
    6. 如果左子节点存在,则它将新节点添加为右子节点。
  5. Inorder() 将以中序方式显示树的节点。
    1. 它遍历整个树,然后打印左子节点,然后是根节点,然后是右子节点。

解决方案

Python

输出

Binary tree after insertion
1 
Binary tree after insertion
2 1 3 
Binary tree after insertion
4 2 5 1 3 
Binary tree after insertion
4 2 5 1 6 3 7 

C

输出

Binary tree after insertion
1 
Binary tree after insertion
2 1 3 
Binary tree after insertion
4 2 5 1 3 
Binary tree after insertion
4 2 5 1 6 3 7 

JAVA

输出

Binary tree after insertion
1 
Binary tree after insertion
2 1 3 
Binary tree after insertion
4 2 5 1 3 
Binary tree after insertion
4 2 5 1 6 3 7

C#

输出

Binary tree after insertion
1 
Binary tree after insertion
2 1 3 
Binary tree after insertion
4 2 5 1 3 
Binary tree after insertion
4 2 5 1 6 3 7 

PHP

输出

Binary tree after insertion
1 
Binary tree after insertion
2 1 3 
Binary tree after insertion
4 2 5 1 3 
Binary tree after insertion
4 2 5 1 6 3 7 
 
下一个主题程序列表