问:将二叉树转换为二叉搜索树的程序。

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

说明

在此程序中,我们需要将给定的二叉树转换为相应的二叉搜索树。如果一个节点最多有两个子节点,则称该树为二叉树。而二叉搜索树是二叉树的一种特殊情况,其中根节点左侧的所有节点都应小于根节点,右侧的节点都应大于根节点。

可以通过将给定的二叉树转换为其相应的数组表示来解决此问题。对数组进行排序。计算数组元素的中间节点,因为它将成为相应二叉搜索树的根节点。

Program to convert Binary Tree to Binary Search Tree

算法

  1. 定义 Node 类,该类包含三个属性:data、left 和 right。这里,left 表示节点的左子节点,right 表示节点的右子节点。
  2. 创建节点时,数据将传递到节点的 data 属性,left 和 right 都将设置为 null。
  3. 定义另一个具有两个属性 root 和 treeArray 的类。
    1. Root 表示树的根节点,并将其初始化为 null。
    2. treeArray 将存储二叉树的数组表示。
  4. convertBTBST() 将把二叉树转换为相应的二叉搜索树
    1. 它将通过调用 convertBTtoArray() 将二叉树转换为相应的数组。
    2. 按升序对步骤 1 生成的数组进行排序。
    3. 通过调用 createBST() 将数组转换为二叉搜索树。
  5. calculateSize() 将计算树中的节点数。
  6. convertBTtoArray() 将通过遍历树并将元素添加到 treeArray 中,将二叉树转换为其数组表示。
  7. createBST() 将通过选择排序的 treeArray 的中间节点作为根节点来创建相应的二叉搜索树。treeArray 将被分成两部分,即 [0, mid-1] 和 [mid+1, end]。递归地从每个数组中查找中间节点,以分别创建左子树和右子树。
  8. Inorder() 将以中序方式显示树的节点,即左子节点后跟根节点,然后是右子节点。

解决方案

Python

输出

Inorder representation of binary tree: 
4 2 5 1 6 3 7 
Inorder representation of resulting binary search tree: 
1 2 3 4 5 6 7 

C

输出

Inorder representation of binary tree: 
4 2 5 1 6 3 7 
Inorder representation of resulting binary search tree: 
1 2 3 4 5 6 7 

JAVA

输出

Inorder representation of binary tree: 
4 2 5 1 6 3 7 
Inorder representation of resulting binary search tree: 
1 2 3 4 5 6 7 

C#

输出

Inorder representation of binary tree: 
4 2 5 1 6 3 7 
Inorder representation of resulting binary search tree: 
1 2 3 4 5 6 7 

PHP

输出

Inorder representation of binary tree: 
4 2 5 1 6 3 7 
Inorder representation of resulting binary search tree: 
1 2 3 4 5 6 7 
 
下一个主题程序列表