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);
- }
- }
- // Function to count the number of leaf nodes in the tree
- int countLeaves(TreeNode* root) {
- if (root == nullptr) {
- return 0; //The tree is empty
- }
- else if (root->left == nullptr && root->right == nullptr) {
- return 1; //Only root node in tree
- }
- else {
- //Count leaf nodes in the left and right subtrees
- int leftLeaves = countLeaves(root->left);
- int rightLeaves = countLeaves(root->right);
- return leftLeaves + rightLeaves;
- }
- }
- 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);
- std::cout << "Count of the number of leaves: ";
- int leafCount = countLeaves(root);
- }
Advertisement
Comments
-
- 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!
- https://bioseanne.com/
Add Comment
Please, Sign In to add comment