Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- #include <iostream>
- struct TreeNode {
- int data; //node value
- TreeNode* left; //pointer to left child
- TreeNode* right; //pointer to right child
- TreeNode(int value) { //constructor for initializing a node
- data = value;
- left = nullptr;
- right = nullptr;
- }
- };
- //insert nodes into tree
- void insert(TreeNode*& root, int value) {
- if (root == nullptr) {
- root = new TreeNode(value);
- }
- else if (value < root->data) {
- insert(root->left, value);
- }
- else {
- insert(root->right, value);
- }
- }
- //Pre-order traversal - you start at the root node and then you visit the left subtree first and then the right
- void printPreOrder(TreeNode* root) {
- if (root != nullptr) {
- std::cout << root->data << " ";
- printPreOrder(root->left);
- printPreOrder(root->right);
- }
- }
- int main()
- {
- TreeNode* root = nullptr;
- int n;
- std::cout << "Enter the number of nodes you will insert: ";
- std::cin >> n;
- for (int i = 0; i < n; i++) {
- int value;
- std::cout << "Enter a value: ";
- std::cin >> value;
- insert(root, value);
- }
- printPreOrder(root);
- }
Advertisement
Add Comment
Please, Sign In to add comment