我意识到这对于
Java程序员来说是一个备受争议,备受争议的话题,但我相信我的问题有点独特.我的算法要求通过引用传递.我正在进行一般树(即n-children)的顺时针/逆时针预先遍历遍历,以分配虚拟(x,y)坐标.这只是意味着当我访问它时,我会计算(并标记)我访问的树的节点.
/**
* Generates a "pre-ordered" list of the nodes contained in this object's subtree
* Note: This is counterclockwise pre-order traversal
*
* @param clockwise set to true for clockwise traversal and false for counterclockwise traversal
*
* @return Iterator list iterator
*/
public Iterator PreOrder(boolean clockwise)
{
LinkedList list = new LinkedList();
if(!clockwise)
PreOCC(this, list);
else
PreO(this,list);
count = 0;
return list.iterator();
}
private void PreOCC(Tree rt, LinkedList list)
{
list.add(rt);
rt.setVirtual_y(count);
count++;
Iterator ci = rt.ChildrenIterator();
while(ci.hasNext())
PreOCC(ci.next(), list);
}
private void PreO(Tree rt, LinkedList list, int count)
{
list.add(rt);
rt.setX_vcoordinate(count);
Iterator ci = rt.ReverseChildrenIterator();
while(ci.hasNext())
PreO(ci.next(), list, ++count);
}
在这里,我生成树的结构:
Tree root = new Tree(new Integer(0));
root.addChild(new Tree(new Integer(1), root));
root.addChild(new Tree(new Integer(2), root));
root.addChild(new Tree(new Integer(3), root));
Iterator ci = root.ChildrenIterator();
ci.next();
Tree select = ci.next();
select.addChild(new Tree(new Integer(4), select));
select.addChild(new Tree(new Integer(5), select));
当我打印遍历节点的顺序以及它分配给相应节点的坐标时,这是我的输出.
0 3 2 5 4 1
0 1 2 3 4 3
0 1 2 4 5 3
0 1 2 3 4 3
注意:前两行是顺时针预先遍历遍历和x坐标的分配.接下来的两行是逆时针预先遍历遍历并分配它们的y坐标.
我的问题是如何让第二行阅读:
0 1 2 3 4 5
编辑1:这是我用来打印我访问节点的顺序和我指定的坐标的代码.
Iterator pre = root.PreOrder(true);
System.out.println(" \t");
while(pre.hasNext())
System.out.print(pre.next() + "\t");
pre = root.PreOrder(true);
System.out.println();
System.out.println("x-coordinates:\t");
while(pre.hasNext())
System.out.print(pre.next().getVirtual_x() + "\t");
System.out.println();
System.out.println();
Iterator preCC = root.PreOrder(false);
System.out.println(" \t");
while(preCC.hasNext())
System.out.print(preCC.next() + "\t");
preCC = root.PreOrder(false);
System.out.println();
System.out.println("x-coordinates:\t");
while(preCC.hasNext())
System.out.print(preCC.next().getVirtual_y() + "\t");
这里还有一个引用,以更好地解释x,y坐标.
顶点.顶点的y坐标.
Compute the counterclockwise
pre-ordering of the vertices of T (the
ordering are numbered from 0 to n −
1), use them as the x-coordinates for
the vertices.
Compute the clockwise pre-ordering of
the vertices of T (the ordering are
numbered from 0 to n − 1), use them as
the y-coordinates for the vertices.