C/C++ Arena

Step 1 of 6

Binary trees and recursion

A binary tree node holds a value and up to two children. Ownership is naturally a tree too, so std::unique_ptr children mean the whole tree frees itself:

struct Node {
    int value;
    std::unique_ptr<Node> left, right;
};

Almost every tree algorithm has the same recursive shape: handle the empty tree (nullptr), then combine the answers from the two subtrees.

int count(const Node* n) {
    if (!n) return 0;
    return 1 + count(n->left.get()) + count(n->right.get());
}

Your turn: write height (an empty tree has height 0, a single node 1) and sum.

Next: Binary search trees