Computer >> Máy Tính >  >> Lập trình >> C ++

Chuyển đổi Cây nhị phân thành Cây phản chiếu của nó trong C ++

Trong hướng dẫn này, chúng ta sẽ thảo luận về một chương trình chuyển đổi một cây nhị phân thành cây nhân bản của nó.

Đối với điều này, chúng tôi sẽ được cung cấp một cây nhị phân. Nhiệm vụ của chúng ta sẽ là hoán đổi các giá trị ở bên trái và đầu bên phải để tạo ra một cây nhân bản từ cây nhị phân đã cho.

Ví dụ

#include<bits/stdc++.h>
using namespace std;
//binary tree node structure
struct Node{
   int data;
   struct Node* left;
   struct Node* right;
};
//creation of a new node with no child nodes
struct Node* newNode(int data){
   struct Node* node = (struct Node*)malloc(sizeof(struct Node));
   node->data = data;
   node->left = NULL;
   node->right = NULL;
   return(node);
}
void mirror(struct Node* node){
   if (node == NULL)
      return;
   else{
      struct Node* temp;
      //swapping the subtrees
      mirror(node->left);
      mirror(node->right);
      temp = node->left;
      node->left = node->right;
      node->right = temp;
   }
}
//printing the inorder traversal
void print_tree(struct Node* node){
   if (node == NULL)
      return;
   print_tree(node->left);
   cout << node->data << " ";
   print_tree(node->right);
}
int main(){
   struct Node *root = newNode(1);
   root->left = newNode(2);
   root->right = newNode(3);
   root->left->left = newNode(4);
   root->left->right = newNode(5);
   //printing the initial tree
   cout << "Inorder traversal of the constructed" << endl;
   print_tree(root);
   mirror(root);
   //printing the mirror tree
   cout << "\nInorder traversal of the mirror tree" << endl;
   print_tree(root);
   return 0;
}

Đầu ra

Inorder traversal of the constructed
4 2 5 1 3
Inorder traversal of the mirror tree
3 1 5 2 4