Question

This is my first time i am studying binary trees, and i see a lot of questions regarding the path traversal, one such question was to find the path of a particular node. This is very easy in a Binary Search Tree, but it's very tough in a normal Binary Tree as the elements in the nodes have no relation between. I came up with many logic but none of them work for all the nodes in the tree. And i would also like to know what is the logic for traversing each and every path from the root to the leaf node.

Thank You.

Was it helpful?

Solution

Use recursion. The details vary depending on exactly how you've defined your tree, but it might look something like this

void visit(TreeNode* node, vector<Node*>& path)
{
    // check for NULL
    if (node == NULL)
        return;
    // add node to path
    path.push_back(node);
    // print the node path
    ...
    // visit left child
    visit(node->left, path);
    // visit right child
    visit(node->right, path);
    // remove node from path
    path.pop_back();
}

// start at the root
vector<Node*> path;
visit(root, path);
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top