【发布时间】:2011-05-02 21:50:04
【问题描述】:
我意识到这对于 Java 程序员来说是一个激烈争论、有争议的话题,但我相信我的问题有些独特。我的算法 REQUIRES 通过引用传递。我正在对一般树(即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<Tree> list iterator
*/
public Iterator<Tree> PreOrder(boolean clockwise)
{
LinkedList<Tree> list = new LinkedList<Tree>();
if(!clockwise)
PreOCC(this, list);
else
PreO(this,list);
count = 0;
return list.iterator();
}
private void PreOCC(Tree rt, LinkedList<Tree> list)
{
list.add(rt);
rt.setVirtual_y(count);
count++;
Iterator<Tree> ci = rt.ChildrenIterator();
while(ci.hasNext())
PreOCC(ci.next(), list);
}
private void PreO(Tree rt, LinkedList<Tree> list, int count)
{
list.add(rt);
rt.setX_vcoordinate(count);
Iterator<Tree> 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<Tree> 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 10 1 2 3 4 3
0 1 2 4 5 30 1 2 3 4 3
注意:前两行是顺时针前序遍历和 x 坐标的分配。接下来的两行是逆时针前序遍历并分配它们的 y 坐标。
我的问题是如何阅读第二行:
0 1 2 3 4 5
编辑 1:这是我用来打印访问节点的顺序和分配的坐标的代码。
Iterator<Tree> 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<Tree> 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 坐标。
逆时针计算 T 的顶点的预排序( 排序从 0 到 n 编号 - 1),将它们用作 x 坐标 顶点。
计算顺时针预排序 T 的顶点(排序为 编号从 0 到 n - 1),将它们用作 顶点的 y 坐标。
【问题讨论】:
-
我同意。这使得更难理解在这里做什么!
-
Nathan 你确定你正在构建的树有你想要的结构吗?我看不到节点的预先遍历将如何按照 012345 的顺序访问它们。
-
@matt:我没有按这个顺序访问他们。访问节点的顺序是最上面一行。我将发布所有这些代码,因为它似乎让很多人感到困惑。
标签: java pass-by-reference graph-theory pass-by-value