【发布时间】:2014-10-17 20:35:40
【问题描述】:
有一个类的数组列表,其值为
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
对象是这样的,它存储了父nodeid(即对于节点d3,Parent(d3)-root。这种关系使得给定节点X和depth=X.depth+1下面的所有节点都是它的子节点。
所以,根孩子是:d3,c4,f5,e6
d3 孩子是:c3,e3,c5
现在,我必须编写一些代码来为其生成中序遍历。 类似:
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
我写过这样的java方法
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);
}
}
}
}
但这不是通用的(如果深度增加/改变它将不起作用)并且也不完整。如何从我拥有的数组列表中进行中序遍历。假设 Arraylist 有节点名称、深度和父节点的序列号。有人可以给我指点吗? 这不是二叉树。
【问题讨论】:
-
我看不到你想要的结果背后的逻辑......无论如何,如果你使用 Guava,你可能想看看(并实施)
TreeTraverser
标签: java arraylist traversal inorder