Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

traversing a non binary tree in java [closed]

Tags:

java

tree

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 ?

like image 593
user2277918 Avatar asked Oct 12 '13 19:10

user2277918


3 Answers

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.

like image 50
An SO User Avatar answered Nov 05 '22 07:11

An SO User


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.

like image 22
Tarik Avatar answered Nov 05 '22 06:11

Tarik


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!

like image 6
Joseph Avatar answered Nov 05 '22 07:11

Joseph