代码之家  ›  专栏  ›  技术社区  ›  Clinton Pierce

检索树结构所有排列的有效方法

  •  2
  • Clinton Pierce  · 技术社区  · 15 年前

    为更大的树编辑,以获取更多示例。

    我有一个树结构,我需要生成所有可能的排列,但有一些限制。给定一棵这样的树:

        A1----(B1, B2)
         \    
          \___(C1)
                 \__(E1, E2)
    /       
    -  A2----(B3, B4)
    \     \     \
           \     \__(D1)
            \
             \_(F1, F2)
                    |
                    (D4)   
    
        A3----(B5, B6)
                    \__(D2, D3)
    

    或者,如果这有点含糊不清,那么这里有相同的结构,用Perl表示法完成:

    my $nodes = [
    {
        name => 'A1',
        children => [
            [ { name => 'B1', children => []  }, 
              { name => 'B2', children => []  }
            ],
            [
              { name => 'C1', 
                        children => [
                            [
                                { name => 'E1', children => [] },
                                { name => 'E2', children => [] }
                            ]
                        ]
                }
            ]
        ]
    },
    {
        name => 'A2',
        children => [
            [ { name => 'B3', 
                    children => [
                        [
                            { name => 'D1', children => [] }
                        ]
                    ] 
              },
              { name => 'B4', children => [] }
            ],
            [
              { name => 'F1', children => [] },
              { name => 'F2', children => [
                            [ { name => 'D4', children => [] } ]
                        ]
                }
            ]
        ]
    },
    {
        name => 'A3',
        children => [
            [ { name => 'B5', children => [] },
              { name => 'B6', children => [
                        [ { name => 'D2', children => [] },
                          { name => 'D3', children => [] }
                        ] 
                    ]                 
                }
            ]
        ]
    }
    
    ];
    

    (坦率地说,如果你能在 可读性 帕尔,我也要这个。)

    我正在寻找穿过这棵树并从顶层向下检索所有可能的“路径”。节点的所有后代组必须由“路径”中的1个成员表示。例如,在A1中,需要表示(b1,b2)和(c1)中的一个。因此,从a1开始的每一条路径都将以以下两种方式开始:

    A1 B1 C1

    A1 B2 C1

    如果b1、b2或c1有孩子,也需要表示这些孩子。

    通过手工计算上述树,我得到了以下可能性:

    A1 B1 C1 E1
    A1 B1 C1 E2
    A1 B2 C1 E1
    A1 B2 C1 E2
    
    A2 B3 D1 F1
    A2 B3 D1 F2 D4
    A2 B4 F1
    A2 B4 F2 D4
    
    A3 B5
    A3 B6 D2
    A3 B6 D3
    

    这里的每个节点都是一个数据行对象:

    internal class DataRow
    {
        internal string tag = "";
        internal int id = 0;
        internal Dictionary<string, List<DataRow>> children = null;
    
        internal DataRow(int id, string tagname)
        {
            this.tag = tagname;
            this.id = id;
        }        internal void AddChildren(string type, List<DataRow> drList)
        {
            if (children == null)
                children = new Dictionary<string, List<DataRow>>();
            if (!children.ContainsKey(type))
                children[type] = new List<DataRow>();
            children[type].AddRange(drList);
        }
        internal void AddChild(string type, DataRow dr)
        {
            List<DataRow> drList = new List<DataRow>();
            drList.Add(dr);
            AddChildren(type, drList);
        }
        public override string ToString()
        {
            return this.tag + " " + this.id;
        }
    }
    

    要在上面构建示例树(E和F级别除外,稍后添加):

            DataRow fullList = new DataRow(null, "");
            DataRow dr, dr2, dr3;
    
            // First node above
            dr = new DataRow(1, "A");
            List<DataRow> drList = new List<DataRow>();
            drList.Add(new DataRow(1, "B"));
            drList.Add(new DataRow(2, "B"));
            dr.AddChildren("B", drList);
            drList.Clear();
            dr2 = new DataRow(1, "C");
            dr2.AddChild("C", new DataRow(1, "E"));
            dr2.AddChild("C", new DataRow(2, "E"));
            drList.Add(dr2);
            dr.AddChildren("C", drList);
            fullList.AddChild("A", dr);
    
    
            // Second Node above (without the "F" stuff)
            drList.Clear();
            dr = new DataRow(3, "B");
            dr.AddChild("D", new DataRow(1, "D"));
            drList.Add(dr);
            drList.Add(new DataRow(4, "B"));
            dr = new DataRow(2, "A");
            dr.AddChildren("B", drList);
            fullList.AddChild("A", dr);
    
            // Third node above
            drList.Clear();
            dr3 = new DataRow(6, "B");
            dr3.AddChild("B", new DataRow(2, "D"));
            dr3.AddChild("B", new DataRow(3, "D"));
            dr2 = new DataRow(3, "A");
            dr2.AddChild("B", new DataRow(5, "B"));
            dr2.AddChild("B", dr3);
            fullList.AddChild("A", dr2);
    

    在整棵树上行走是微不足道的:

        internal void PermutedList()
        {
            if ( children == null ) return;
            foreach (string kidType in children.Keys)
            {
                foreach (DataRow dr in children[kidType])
                {
                    dr.PermutedList();
                }
            }
        }
    

    但这不是我需要的。这个问题是一个完整的树行走,但以一个特定的顺序。我没有得到什么?这是什么样的散步?

    我在10年前用Perl编写的代码中有一个混乱且缓慢的实现,但我无法再破译我自己的代码(真丢脸!).

    编辑: 下面的图表和列表已经展开,代码还没有展开。

    如果我能描述这个图,我就可以编制它。如果我知道它叫什么,我可以查一下。但我不能。所以让我再解释一下。

    桶名不重要!

    每个节点都有“子桶”。A1有两个桶,一个包含“B”,另一个包含“C”。如果这就是它所拥有的一切(而且C下面没有桶),我会有“a1 b1 c1”和“a1 b2 c1”——至少一个来自所有子桶的代表。

    所以我认为每个桶都需要它的子代的叉积(一直向下)。

    4 回复  |  直到 15 年前
        1
  •  2
  •   Greg Bacon    15 年前

    使用以下子项:

    use 5.10.0;  # for // (aka defined-or)
    
    use subs 'enumerate';
    sub enumerate {
      my($root) = @_;
    
      my $kids = $root->{children};
      return [ $root->{name} // () ]
        unless @$kids;
    
      my @results;
      foreach my $node (@{ $kids->[0] }) {
        my @fronts = map [ $root->{name} // (), @$_ ],
                         enumerate $node;
    
        my @below = enumerate {
          name => undef,
          children => [ @{$kids}[1 .. $#$kids ] ],
        };
    
        foreach my $a (@fronts) {
          foreach my $b (@below) {
            push @results => [ @$a, @$b ];
          }
        }
      }
    
      @results;
    }
    

    你可以用

    foreach my $tree (@$nodes) {
      foreach my $path (enumerate $tree) {
        print "@$path\n";
      }
    
      print "\n";
    }
    

    要获得以下输出:

    A1 B1 C1 E1
    A1 B1 C1 E2
    A1 B2 C1 E1
    A1 B2 C1 E2
    
    A2 B3 D1 F1
    A2 B3 D1 F2 D4
    A2 B4 F1
    A2 B4 F2 D4
    
    A3 B5
    A3 B6 D2
    A3 B6 D3

    我用过 $path 上面,但是它会严重混淆维护代码的任何人,因为路径有一个很好理解的含义。你可以完全巧妙地避开命名问题:

    print join "\n" =>
          map { join "" => map "@$_\n", @$_ }
          map [ enumerate($_) ] => @$nodes;
    
        2
  •  1
  •   Kwal    15 年前

    每个节点都应该知道其父节点(getParentRow),这样您就可以将父节点作为参数传递给递归方法。这样,当您到达一个“叶”时,您可以递归地跟踪到根目录。

    我不确定它是否是最有效的方法,但我认为它应该给你想要的结果。

        3
  •  1
  •   Jeffrey L Whitledge    15 年前

    可以按照以下所需的任意顺序执行树行走。对于根节点,将所有子节点放入数据结构(如下所述)。然后从数据结构中取出一个节点,并将其所有子节点放入数据结构中。继续,直到数据结构为空。

    诀窍是选择正确的数据结构。对于顺序(深度优先)遍历,可以使用堆栈。(子项必须按相反的顺序推到堆栈上。)要进行深度优先遍历,可以使用队列。

    对于更复杂的订单,优先级队列是票据。只需根据您希望遍历树的顺序,根据您使用的任何条件设置优先级。事实上,正确设置优先级也将表现为堆栈或队列,分别导致前面提到的深度优先顺序和宽度优先顺序。

    编辑添加:

    树遍历算法对于这种类型的数据结构非常有效,因为它没有循环。只需在数据结构中为集合中的每个项放置一个新节点。我想唯一额外的就是一种表示路径的方法。

    这条路很容易走。你只需要这样的东西:

    class Path<T>
    {
        T lastNode;
        Path<T> previousNodes;
        public Path(T lastNode, Path<T> previousNodes)
        {
            this.lastNode = lastNode; this.previousNodes = previousNodes;
        }
        public IEnumerable<T> AllNodes()
        {
            return AllNodesBackwards().Reverse();
        }
        private IEnumerable<T> AllNodesBackwards()
        {
            Path<T> currentPath = this;
            while (currentPath != null)
            {
                yield return currentPath.lastNode;
                currentPath = currentPath.previousNodes;
            }
        }
        public T Node { get { return lastNode; } }
    }
    

    所以我们要做的就是沿着这条路走。与此类似的事情应该会起作用:

    [删除了不正确的解决方案]

    再次编辑:

    好吧,我终于知道你想要什么了。在下树之前,你想在每一条小路上横穿不同“孩子类型”的孩子。

    这是一个大混乱,但我解决了它:

    public void WalkPath2()
    {
        Queue<Path<DataRow>> queue = new Queue<Path<DataRow>>();
        queue.Enqueue(new Path<DataRow>(this, null));
    
        while (queue.Count > 0)
        {
            Path<DataRow> currentPath = queue.Dequeue();
            DataRow currentNode = currentPath.Node;
    
            if (currentNode.children != null)
            {
                foreach (Path<DataRow> nextPath in currentNode.GetChildPermutations(currentPath))
                    queue.Enqueue(nextPath);
            }
            else
            {
                foreach (DataRow node in currentPath.AllNodes())
                {
                    Console.Write(node.ToString());
                    Console.Write("      ");
                }
                Console.WriteLine();
            }
    
        }
    
    }
    
    private IEnumerable<Path<DataRow>> GetChildPermutations(Path<DataRow> currentPath)
    {
        string firstLevelKidType = null;
        foreach (string kidType in children.Keys)
        {
            firstLevelKidType = kidType;
            break;
        }
        foreach (Path<DataRow> pathPermutation in GetNextLevelPermutations(currentPath, firstLevelKidType))
            yield return pathPermutation;
    }
    
    private IEnumerable<Path<DataRow>> GetNextLevelPermutations(Path<DataRow> currentPath, string thisLevelKidType)
    {
        string nextLevelKidType = null;
        bool nextKidTypeIsTheOne = false;
        foreach (string kidType in children.Keys)
        {
            if (kidType == thisLevelKidType)
                nextKidTypeIsTheOne = true;
            else
            {
                if (nextKidTypeIsTheOne)
                {
                    nextLevelKidType = kidType;
                    break;
                }
            }
        }
    
        foreach (DataRow node in children[thisLevelKidType])
        {
            Path<DataRow> nextLevelPath = new Path<DataRow>(node, currentPath);
            if (nextLevelKidType != null)
            {
                foreach (Path<DataRow> pathPermutation in GetNextLevelPermutations(nextLevelPath, nextLevelKidType))
                    yield return pathPermutation;
            }
            else
            {
                yield return new Path<DataRow>(node, currentPath);
            }
        }
    
    
    }
    
        4
  •  0
  •   Paul Nathan    15 年前

    首先我以为你想要所有的树。 http://en.wikipedia.org/wiki/Spanning_tree

    但后来我意识到你想要的是从树根开始的“跨越式行走”。

    然后我意识到这是(相对)简单的。

    Foreach leaf
    
    Walk from the leaf to the root
    
    end for
    

    当然,您需要一个真正的数据结构,我认为Perl散列的散列不起作用;您需要在每个节点中有一个“父”指针。