Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Tree traversal - starting at leaves with only parent pointers?

Is it conceptually possible to have a tree where you traverse it by starting at a given leaf node (rather than the root node) and use parent pointers to get to the root?

I ask this since I saw someone implement a tree and they used an array to hold all of the leaf nodes/external nodes and each of the leaf/external nodes point only to their parent nodes and those parent point to their parent node etc. until you get to the root node which has no parents. Their implementation thus would require you to start at one of the leaves to get to anywhere in the tree and you would cannot go "down" the tree since her tree nodes do not have any children pointers, only parent pointers.

I found this implementation interesting since I haven't seen anything like it but I was curious if it could still be considered it a "tree". I have never seen a tree where you start traversal at the leaves, instead of root. I have also never seen a tree where the tree nodes only have parent pointers and no children pointers.

like image 451
user2157871 Avatar asked Mar 11 '13 17:03

user2157871


People also ask

How do you traverse a tree from a leaf?

Traverse an n-ary tree, starting from a leaf node, up to the root, such that no node is traversed before all it's children are traversed. First node traversed will always be the leaf node, last node traversed will always be the root node.

How do you root a traverse leaf?

Use a path array path[] to store current root to leaf path. Traverse from root to all leaves in top-down fashion. While traversing, store data of all nodes in current path in array path[]. When we reach a leaf node, print the path array.

What is parent pointer?

In computer science, an in-tree or parent pointer tree is an N-ary tree data structure in which each node has a pointer to its parent node, but no pointers to child nodes.

How do you traverse a tree bottom up?

First print string of left most subtree(from bottom to top) then print string of second left subtree(from bottom to top) then print for third left subtree and so on.


1 Answers

Yep, this structure exists. It's often called a spaghetti stack.

Spaghetti stacks are useful for representing the "is a part of" relation. For example, if you want to represent a class hierarchy in a way that makes upcasting efficient, then you might represent the class hierarchy as a spaghetti stack in which the node for each type stores a pointer to its parent type. That way, it's easy to find whether an upcast is valid by just walking upward from the node.

They're also often used in compilers to track scoping information. Each node represents one scope in the program, and each node has a pointer to the node representing the scope one level above it.

Hope this helps!

like image 145
templatetypedef Avatar answered Sep 21 '22 18:09

templatetypedef