S SmartDocs
Series: Algorithms cpp 109 lines · Updated 2026-03-02

btree-travaseral.cpp

Algorithms/btree-travaseral.cpp

#include <iostream>
using namespace std;

// define tree node

struct Node {
    int data;
    Node* left;
    Node* right;

    Node(int value) {
        data = value;
        left = nullptr;
        right = nullptr;
    }
}

// Pre-order Traversal
void preOrder(Node* root) {
    if (root == nullptr) {
        return;
    }
    cout << root->data << " ";  // Visit the current node
    preOrder(root->left);       // Traverse the left subtree
    preOrder(root->right);      // Traverse the right subtree
}

// In-order Traversal
void inOrder(Node* root) {
    if (root == nullptr) {
        return;
    }
    inOrder(root->left);    // Traverse the left subtree
    cout << root->data << " ";  // Visit the current node
    inOrder(root->right);   // Traverse the right subtree
}

// Post-order Traversal
void postOrder(Node* root) {
    if (root == nullptr) {
        return;
    }
    postOrder(root->left);  // Traverse the left subtree
    postOrder(root->right); // Traverse the right subtree
    cout << root->data << " ";  // Visit the current node
}

// countLeaves
int countLeaves(Node* root) {
    if (root == nullptr) {
        return 0;
    }
    if (root->left == nullptr && root->right == nullptr) {
        return 1;
    }
    return countLeaves(root->left) + countLeaves(root->right);
}

// calculateHeight
int calculateHeight(Node* root) {
    if (root == nullptr) {
        return 0;
    }
    int leftHeight = calculateHeight(root->left);
    int rightHeight = calculateHeight(root->right);
    return 1 + max(leftHeight, rightHeight);
}

int main() {
    // Construct a balanced binary tree
    /*
            1
           / \
          2   3
         / \ / \
        4  5 6  7
    */

    Node* root = new Node(1);
    root->left = new Node(2);
    root->right = new Node(3);

    root->left->left = new Node(4);
    root->left->right = new Node(5);

    root->right->left = new Node(6);
    root->right->right = new Node(7);

    // Traversals
    cout << "Pre-order: ";
    preOrder(root);
    cout << endl;

    cout << "In-order: ";
    inOrder(root);
    cout << endl;

    cout << "Post-order: ";
    postOrder(root);
    cout << endl;

    // Count leaves
    cout << "Number of leaves: " << countLeaves(root) << endl;

    // Calculate height
    cout << "Height of tree: " << calculateHeight(root) << endl;

    return 0;
}

Related articles