BlackWolfy

Binary Tree (Pre-order traversal)

Nov 1st, 2023
909
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C++ 1.22 KB | None | 0 0
  1. #include <iostream>
  2.  
  3. struct TreeNode {
  4.     int data;           //node value
  5.     TreeNode* left;     //pointer to left child
  6.     TreeNode* right;    //pointer to right child
  7.  
  8.     TreeNode(int value) {   //constructor for initializing a node
  9.         data = value;
  10.         left = nullptr;
  11.         right = nullptr;
  12.     }
  13. };
  14. //insert nodes into tree
  15. void insert(TreeNode*& root, int value) {
  16.     if (root == nullptr) {
  17.         root = new TreeNode(value);
  18.     }
  19.     else if (value < root->data) {
  20.         insert(root->left, value);
  21.     }
  22.     else {
  23.         insert(root->right, value);
  24.     }
  25. }
  26. //Pre-order traversal - you start at the root node and then you visit the left subtree first and then the right
  27. void printPreOrder(TreeNode* root) {
  28.     if (root != nullptr) {
  29.         std::cout << root->data << " ";
  30.         printPreOrder(root->left);
  31.         printPreOrder(root->right);
  32.     }
  33. }
  34. int main()
  35. {
  36.     TreeNode* root = nullptr;
  37.     int n;
  38.     std::cout << "Enter the number of nodes you will insert: ";
  39.     std::cin >> n;
  40.     for (int i = 0; i < n; i++) {
  41.         int value;
  42.         std::cout << "Enter a value: ";
  43.         std::cin >> value;
  44.         insert(root, value);
  45.     }
  46.     printPreOrder(root);
  47. }
Advertisement
Add Comment
Please, Sign In to add comment