Computer >> Hướng Dẫn Máy Tính >  >> Lập Trình >> C++

Chuyển cây tìm kiếm nhị phân (BST) thành Max Heap trong C++


Cho BST, chuyển thành Max Heap sao cho thứ tự postorder của Max Heap bằng inorder của BST.

Giải pháp: Inorder BST -> mảng tăng dần. Postorder traversal cây, gán giá trị từ mảng theo thứ tự.

Chương trình minh họa

#include <bits/stdc++.h>
using namespace std;
struct Node { int data; Node *left, *right; };
Node* getNode(int data){
    Node* n = new Node; n->data = data; n->left = n->right = NULL; return n;
}
void inorderTraversal(Node* root, vector<int>& arr){
    if (!root) 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) 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(){
    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 << "Postorder Traversal (Max Heap):\n";
    postorderTraversal(root);
    return 0;
}

Kết quả

Postorder Traversal: 1 2 3 4 5 6 7