0

有一些类的数组列表,其值为

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

该对象是这样的,它具有存储的父节点ID(即对于节点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 有节点名称、深度和父节点的序列号。有人可以给我指点吗?这不是二叉树。

4

1 回答 1

0

首先,您绝对想先获取ArrayList并从中构造一棵树。您真的不想尝试数据结构的中序遍历,而它仍然表示为ArrayList. 这是你的第一个任务。

一旦你这样做了,中序遍历就很容易了。它有这个方案:

  1. 递归探索左孩子;
  2. 处理这个节点;
  3. 递归探索正确的孩子。

但是,您有一个主要问题,那就是您说这不是二叉树。中序遍历只为二叉树定义,因为你必须先做左边的事情,然后是当前节点,然后是右边的路径。这对于任何其他类型的树都没有很好的定义。

于 2014-10-17T20:43:51.440 回答