我需要找到一种算法来生成二叉树的所有可能排列,并且需要在不使用列表的情况下这样做(这是因为树本身带有无法转换为列表的语义和约束)。我找到了一种适用于高度为 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
等等...