Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- // http://code2begin.blogspot.com
- // program to mirror a binary tree iteratively
- #include <iostream>
- using namespace std;
- // node class
- class node{
- public:
- int data;
- node* left;
- node* right;
- };
- // function that returns a pointer to new node
- node* createNode(int element){
- node* temp = (node*) malloc(sizeof(node));
- temp->data = element;
- temp->left = NULL;
- temp->right = NULL;
- return temp;
- }
- // function to convert tree into mirror tree iteratively
- void mirror_tree(node* root){
- // if the node is null then return
- if (root == NULL){
- return;
- }
- // creating a stack to keep the child pointers
- stack<node *> STACK;
- // push root node on the stack
- STACK.push(root);
- while (!STACK.empty()){
- // remove the top node from the stack
- node *current = STACK.top();
- STACK.pop();
- // swap the left and right nodes
- node* temp = current->left;
- current->left = current->right;
- current->right = temp;
- // as it is a stack, we push right child node first because we want to access it after operating on the left child
- if (current->right != NULL){
- STACK.push(current->right);
- }
- if (current->left != NULL){
- STACK.push(current->left);
- }
- }
- }
- int main() {
- node* m1 = createNode(8);
- m1->left = createNode(3);
- m1->right = createNode(10);
- m1->left->left = createNode(1);
- m1->left->right = createNode(6);
- m1->left->right->left = createNode(4);
- m1->left->right->right = createNode(7);
- m1->right->right = createNode(14);
- m1->right->right->left = createNode(13);
- node* m2 = createNode(8);
- m2->right = createNode(3);
- m2->left = createNode(10);
- m2->left->left = createNode(14);
- m2->right->left = createNode(6);
- m2->right->right = createNode(1);
- m2->left->left->right = createNode(13);
- m2->right->left->left = createNode(7);
- m2->right->left->right = createNode(4);
- cout<<"Tree #1 before mirroring : ";
- preorder(m1);
- cout<<endl;
- cout<<"Tree #1 after mirroring : ";
- mirror_tree(m1);
- preorder(m1);
- cout<<endl;
- cout<<"\n\nTree #2 is mirror of Tree #1 to check the correctness : "<<endl;
- cout<<"TREE #1 : ";
- preorder(m1);
- cout<<endl;
- cout<<"TREE #2 : ";
- preorder(m2);
- cout<<endl;
- }
- /*
- Tree #1 before mirroring : 8 3 1 6 4 7 10 14 13
- Tree #1 after mirroring : 8 10 14 13 3 6 7 4 1
- Tree #2 is mirror of Tree #1 to check the correctness :
- TREE #1 : 8 10 14 13 3 6 7 4 1
- TREE #2 : 8 10 14 13 3 6 7 4 1
- Process finished with exit code 0
- */
Add Comment
Please, Sign In to add comment