【问题标题】:arraylist inorder traversal in javajava中的arraylist中序遍历
【发布时间】: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。这种关系使得给定节点Xdepth=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


【解决方案1】:

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

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

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

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

【讨论】:

    猜你喜欢
    • 2013-12-26
    • 2014-10-21
    • 2015-02-13
    • 1970-01-01
    • 2019-04-19
    • 2013-04-05
    • 1970-01-01
    • 2015-11-28
    • 2013-05-05
    相关资源
    最近更新 更多