BlackWolfy

Binary Tree + Counting the leaves (Pre-order traversal)

Nov 1st, 2023 (edited)
1,091
0
Never
1
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C++ 1.81 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. // Function to count the number of leaf nodes in the tree
  35. int countLeaves(TreeNode* root) {
  36.     if (root == nullptr) {
  37.         return 0; //The tree is empty
  38.     }
  39.     else if (root->left == nullptr && root->right == nullptr) {
  40.         return 1; //Only root node in tree
  41.     }
  42.     else {
  43.         //Count leaf nodes in the left and right subtrees
  44.         int leftLeaves = countLeaves(root->left);
  45.         int rightLeaves = countLeaves(root->right);
  46.         return leftLeaves + rightLeaves;
  47.     }
  48. }
  49. int main()
  50. {
  51.     TreeNode* root = nullptr;
  52.     int n;
  53.     std::cout << "Enter the number of nodes you will insert: ";
  54.     std::cin >> n;
  55.     for (int i = 0; i < n; i++) {
  56.         int value;
  57.         std::cout << "Enter a value: ";
  58.         std::cin >> value;
  59.         insert(root, value);
  60.     }
  61.     printPreOrder(root);
  62.     std::cout << "Count of the number of leaves: ";
  63.     int leafCount = countLeaves(root);
  64. }
Advertisement
Comments
  • Alexey444ik
    2 years
    # text 0.30 KB | 0 0
    1. Hi, I'm Stefani, creator of "A Medical Guide to Beauty, Diet, and Health" blog. I share evidence-based tips on skincare, nutrition, and wellness. I'm passionate about collagen supplements and mental health. My goal is to empower others to live their best lives. Thanks for reading!
    2. https://bioseanne.com/
Add Comment
Please, Sign In to add comment