There is an arraylist of some class with values as
Node,Depth,Value
root,0,-2147483647
d3,1,4
e3,2,0
c5,2,0
c3,2,-3
c4,1,4
e3,2,0
c5,2,0
c3,2,-3
e6,1,4
d6,2,0
f4,2,0
f6,2,-3
f5,1,4
d6,2,0
f4,2,0
f6,2,-3
The object is such that it has the parent nodeid stored (ie for node d3 ,Parent(d3)-root. The relation is such that all the nodes below a given node X
with depth=X.depth+1
are its children. So, Root children are : d3,c4,f5,e6
d3 children are : c3
, e3
, c5
Now, I have to write some code to generate the inorder traversal for it. something like :
root,0,-2147483647
d3,1,4
e3,2,0
d3,1,4
c5,2,0
d3,1,4
c3,2,-3
d3,1,4
root,0,-2147483647
c4,1,4
e3,2,0
c4,1,4
c5,2,0
c4,1,4
c3,2,-3
c4,1,4
root,0,-2147483647
e6,1,4
d6,2,0
e6,1,4
f4,2,0
e6,1,4
f6,2,-3
e6,1,4
root,0,-2147483647
f5,1,4
d6,2,0
f5,1,4
f4,2,0
f5,1,4
f6,2,-3
f5,1,4
root,0,-2147483647
I have written a java method like this
private static void inordertraversal() {
ListIterator <nextmove> iter = nmstack.listIterator();
while(iter.hasNext())
{
nextmove node=iter.next();
if(node.depth==CutoffDepth)
{
maxdepth=true;
}
if (!maxdepth)
{
System.out.println(node.To.Name+","+node.depth+","+node.weight);
}
else
{
nextmove parent=findparent(node.parent);
if (node.parent!=0)
{
System.out.println(node.To.Name+","+node.depth+","+node.weight);
System.out.println(parent.To.Name+","+parent.depth+","+parent.weight);
}
else
{
System.out.println(parent.To.Name+","+parent.depth+","+parent.weight);
System.out.println(node.To.Name+","+node.depth+","+node.weight);
}
}
}
}
But this is not GENERIC(if the depth is increased/changed it will not work) and incomplete as well. How do do this inorder traversal from the arraylist I have. Assume that the Arraylist has Node name,its depth and its parent's serial number. Could someone give me a pointer? This is not a binary tree.
First off, you absolutely want to take the ArrayList
and construct a tree from it first. You really don't want to try an inorder traversal of the data structure while it's still represented as an ArrayList
. That's your first task.
Once you've done that, an inorder traversal is pretty easy. It has this scheme:
You have one major problem, though, which is that you say this is not a binary tree . Inorder traversal is only defined for binary trees , because you have to do the left-hand thing first, then the current node, then the right-hand path. That is not well defined for any other type of tree.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.