Double Tree with examples in C++ Program

C++Server Side ProgrammingProgramming

In this tutorial, we are going to learn how to double the given tree.

Let's see the steps to solve the problem.

  • Create node class.

  • Initialize the tree with dummy data.

  • Write a recursive function to double the tree.

    • Recursively traverse through the tree.

    • Store the left node in a variable.

    • After traversing add the data by creating a new node.

    • Now, add the left node to the newly created node as a left child.

  • Print the tree.

Example

Let's see the code.

 Live Demo

#include <bits/stdc++.h>
using namespace std;
class node {
   public:
   int data;
   node* left;
   node* right;
};
node* newNode(int data) {
   node* Node = new node();
   Node->data = data;
   Node->left = NULL;
   Node->right = NULL;
   return Node;
}
void doubleTree(node* Node) {
   node* oldLeft;
   if (Node == NULL) return;
      doubleTree(Node->left);
   doubleTree(Node->right);
   oldLeft = Node->left;
   Node->left = newNode(Node->data);
   Node->left->left = oldLeft;
}
void printTree(node* node) {
   if (node == NULL) {
      return;
   }
   printTree(node->left);
   cout << node->data << " ";
   printTree(node->right);
}
int main() {
   node *root = newNode(1);
   root->left = newNode(2);
   root->right = newNode(3);
   cout << "Original Tree" << endl;
   printTree(root);
   cout << endl;
   doubleTree(root);
   cout << "Double Tree" << endl;
   printTree(root);
   cout << endl;
   return 0;
}

Output

If you run the above code, then you will get the following result.

Original Tree
2 1 3
Double Tree
2 2 1 1 3 3

Conclusion

If you have any queries in the tutorial, mention them in the comment section.

raja
Published on 28-Jan-2021 06:56:27
Advertisements