在本教程中,我们将讨论将二进制搜索树转换为最大堆的程序。
为此,我们将提供一个二进制搜索树。我们的任务是将给定的二进制搜索树转换为最大堆,以便在元素与自身进行比较时遵循二进制搜索树的条件。
#include <bits/stdc++.h> using namespace std; //BST的节点结构 struct Node { int data; Node *left, *right; }; //节点创建 struct Node* getNode(int data) { struct Node* newNode = new Node; newNode->data = data; newNode->left = newNode->right = NULL; return newNode; } //执行订单遍历 void postorderTraversal(Node*); //使用顺序遍历以排序方式移动 void inorderTraversal(Node* root, vector<int>& arr) { if (root == NULL) return; inorderTraversal(root->left, arr); arr.push_back(root->data); inorderTraversal(root->right, arr); } void convert_BSTHeap(Node* root, vector<int> arr, int* i){ if (root == NULL) return; convert_BSTHeap(root->left, arr, i); convert_BSTHeap(root->right, arr, i); //将数据从数组复制到节点 root->data = arr[++*i]; } //转换为最大堆 void convert_maxheap(Node* root) { vector<int> arr; int i = -1; inorderTraversal(root, arr); convert_BSTHeap(root, arr, &i); } //打印后订单遍历 void postorderTraversal(Node* root) { if (!root) return; postorderTraversal(root->left); postorderTraversal(root->right); cout << root->data << " "; } int main() { struct Node* root = getNode(4); root->left = getNode(2); root->right = getNode(6); root->left->left = getNode(1); root->left->right = getNode(3); root->right->left = getNode(5); root->right->right = getNode(7); convert_maxheap(root); cout << "后置遍历:" << endl; postorderTraversal(root); return 0; }
输出结果
后置遍历: 1 2 3 4 5 6 7