BlackWolfy

Constructed Binary Tree(Pre-order traversal)

Nov 1st, 2023
1,005
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C++ 0.93 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. //Pre-order traversal - you start at the root node and then you visit the left subtree first and then the right
  15. void printPreOrder(TreeNode* root) {
  16.     if (root != nullptr) {
  17.         std::cout << root->data << " ";
  18.         printPreOrder(root->left);
  19.         printPreOrder(root->right);
  20.     }
  21. }
  22. int main()
  23. {
  24.     TreeNode* root = new TreeNode(1);
  25.     root->left = new TreeNode(3);
  26.     root->right = new TreeNode(4);
  27.     root->left->left = new TreeNode(5);
  28.     root->left->right = new TreeNode(8);
  29.  
  30.     printPreOrder(root);
  31. }
  32. //          1
  33. //         / \
  34. //        3   4
  35. //       / \
  36. //      5   8
Advertisement
Add Comment
Please, Sign In to add comment