I have a tree which is not a binary tree and each node has more that 2 children, I am looking for an algorithm traverse the tree, I am really new in learning data structure, I know how to traverse a binary tree but I get lost when it comes to traverse a non-binary tree . Could any one gives me a hint ?
In a non-binary tree, there will be a Vector
or some other structure that has references to all the children. Make a recursive method as so:
public void traverse(Node child){ // post order traversal
for(Node each : child.getChildren()){
traverse(each);
}
this.printData();
}
Something along those lines.
Well, when traversing a binary tree, in preorder, you visit the parent node, then recursively traverse the left subtree then recursively traverse the right subtree. With a tree with more than two children, you recursively traverse the subtrees headed by each children. You would do the recursive calls in a for loop.
You'll need to use recursion since you can't determine how many children are at each node (breadth) or how far the tree goes (depth). Depending on how you want to traverse, you can use Breadth-first-search or Depth-first-search.
There is a ton of information on this topic, so give it an attempt to implement one of these recursive methods and please come back if you have trouble along the way!
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With