0

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.

user3020666
  • 25
  • 1
  • 4
  • Without providing any code, this is hardly a c++ question... – SBI Nov 22 '13 at 07:13
  • i use c++ for these programs, and i need a logic, i don't think that requires some code. – user3020666 Nov 22 '13 at 07:16
  • Might help - http://stackoverflow.com/questions/5691926/traverse-every-unique-path-from-root-to-leaf-in-an-arbitrary-tree-structure – pratim_b Nov 22 '13 at 07:19
  • @user3020666 Code is usually independent of logic ;) It's really just a question about binary trees, is what I'm trying to say. – SBI Nov 22 '13 at 07:24
  • You say "traversing each and every path", which sounds like a lot of work, possibly exponential in nature, but you could have said "visiting every node it the tree" which sounds like an O(n) task and is common place. Search the web for Depth-First-Search or Breadth-First-Search for guide on how ot do it. (note DFS is usually easier if you want to print the path). – RichardPlunkett Nov 22 '13 at 10:47

1 Answers1

1

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);
john
  • 85,011
  • 4
  • 57
  • 81
  • Same question i asked Sam : This logic is right for traversal, but for example if the question is to print the path of an element, then how to do it ? – user3020666 Nov 22 '13 at 07:33
  • @user3020666 If your tree has a `parent` field then you can get the path just by following the parent links. If not then all you have to do is remember the path on your way down the tree. Add a `path` parameter to `visit` and add nodes to it as you go down the tree (and maybe remove nodes from it as you go back up the tree). – john Nov 22 '13 at 07:38