Typical n-ary tree representation

suggest change

An n-ary tree allows each node to have any number of children. In modern C++, a std::vector of owning smart pointers expresses that relationship directly and releases the entire subtree automatically.

Traversal visits each child and recursively visits its descendants. The recursive version below is concise, but a very deep tree may require an explicit stack to avoid exhausting the call stack.

If upward traversal is needed, a node can also store a non-owning parent pointer. The children should remain the sole owners so that ownership is unambiguous.

The helper carries the current depth so it can indent each level:

#include <iostream>
#include <memory>
#include <string>
#include <vector>

struct Node {
    std::string data;
    std::vector<std::unique_ptr<Node>> children;
};

void print_tree(const Node& node, std::size_t depth = 0) {
    std::cout << std::string(depth * 2, ' ') << node.data << '\n';
    for (const auto& child : node.children) {
        print_tree(*child, depth + 1);
    }
}

Feedback about page:

Feedback:
Optional: your email if you want me to get back to you:



Table Of Contents