If you have any query feel free to chat us!
Happy Coding! Happy Learning!
Here's the code to create a binary tree in C++ using a class-based approach:
cppCopy code
#include <iostream> class Node { public: int data; Node* left; Node* right; Node(int val) { data = val; left = nullptr; right = nullptr; } }; class BinaryTree { public: Node* root; BinaryTree() { root = nullptr; } void insert(int val) { insertRecursive(root, val); } private: void insertRecursive(Node* ¤t, int val) { if (current == nullptr) { current = new Node(val); return; } if (val < current->data) insertRecursive(current->left, val); else insertRecursive(current->right, val); } }; // Function to perform inorder traversal for verification void inorderTraversal(Node* root) { if (root) { inorderTraversal(root->left); std::cout << root->data << " "; inorderTraversal(root->right); } } int main() { int arr[] = {5, 2, 8, 1, 3, 7, 9}; int n = sizeof(arr) / sizeof(arr[0]); BinaryTree binaryTree; for (int i = 0; i < n; i++) { binaryTree.insert(arr[i]); } // Verify the created binary tree by performing inorder traversal std::cout << "Inorder Traversal: "; inorderTraversal(binaryTree.root); std::cout << std::endl; // Remember to free the allocated memory after use to avoid memory leaks. // (This is not included in this example for simplicity.) return 0; }In this code, we define a
Nodeclass to represent the nodes of the binary tree and aBinaryTreeclass to handle the tree operations. TheBinaryTreeclass contains arootpointer to the root node of the binary tree. We provide aninsertfunction in theBinaryTreeclass to insert elements into the binary tree using a recursive helper functioninsertRecursive.The main function creates a binary tree object, inserts elements from the array
arrinto the binary tree, and then verifies the created binary tree by performing an inorder traversal using theinorderTraversalfunction.Remember to free the allocated memory for the nodes after use to avoid memory leaks. This can be done by adding a destructor to the
BinaryTreeclass to recursively delete the nodes in the destructor.
Start the conversation!
Be the first to share your thoughts
Quick answers to common questions about our courses, quizzes, and learning platform
Didn't find what you're looking for?
Contact Support