代码之家  ›  专栏  ›  技术社区  ›  Mia Clarke

不使用列表排列二叉树

  •  2
  • Mia Clarke  · 技术社区  · 17 年前

    我需要找到一个算法来生成二叉树的每一个可能的排列,并且需要在不使用列表的情况下这样做(这是因为树本身带有无法转换为列表的语义和约束)。我发现了一种算法,它适用于高度为3或更低的树,但每当我达到更高的高度时,我就会在每增加一个高度时释放一组可能的排列。

    我目前使用的算法可以这样描述:

    if the left child node has been swapped
          swap my right node with the left child nodes right node
          set the left child node as 'unswapped'
      if the current node is back to its original state
          swap my right node with the lowest left nodes' right node
          swap the lowest left nodes two childnodes
          set my left node as 'unswapped'
          set my left chilnode to use this as it's original state
          set this node as swapped
          return null
      return this; 
    else if the left child has not been swapped
      if the result of trying to permute left child is null
         return the permutation of this node
      else 
         return the permutation of the left child node
    if this node has a left node and a right node that are both leaves
       swap them
       set this node to be 'swapped'
    

    算法的预期行为如下所示:

                branch
                 /    |
           branch     3
             /   |
       branch    2
       /     |
      0      1
    
    
                branch
                 /    |
           branch     3
             /   |
       branch    2        
       /     |
      1      0           <-- first swap
    
    
    
                branch
                 /    |
           branch     3
             /   |
       branch    1         <-- second swap
       /     |
      2      0
    
    
    
                branch
                 /    |
           branch     3
             /   |
       branch    1         
       /     |
      0      2   <-- third swap
    
    
                branch
                 /    |
           branch     3
             /   |
       branch    0   <-- fourth swap        
       /     |
      1      2  
    

    等等

    2 回复  |  直到 12 年前
        1
  •  3
  •   Welbog    17 年前

    这个结构完全不适合排列,但是既然你知道它是左中心的,你也许可以做出一些假设来帮助你。

    我试着用一种与你类似的方式来处理它,但我总是发现,你只有一条二进制信息(交换或不交换),这是不够的。四片叶子,你有四片!(24)可能的组合,但实际上只有三个分支(3位,8个可能的组合)来存储交换的状态信息。你根本没有地方存储这些信息。

    差不多

    For each permutation
       Encode the permutation as a series of swaps from the original
       Run these swaps on the original tree
       Do whatever processing is needed on the swapped tree
    

        2
  •  0
  •   HUAGHAGUAH    17 年前

    列出树中的所有项目,使用生成方法构建所有可能的顺序(参见Knuth Vol 4),然后将它们重新映射到树结构,这有什么错?