【发布时间】:2009-03-26 12:24:24
【问题描述】:
我需要找到一种算法来生成二叉树的所有可能排列,并且需要在不使用列表的情况下这样做(这是因为树本身带有无法转换为列表的语义和约束)。我找到了一种适用于高度为 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
等等……
【问题讨论】:
-
闻起来像家庭作业,但看起来你付出了真正的努力,所以这比通常的家庭作业式问题要好得多。尽管如此,即使是家庭作业,这种数据结构也很不适合置换。
-
恐怕这不是家庭作业(我希望是),我有一份真正的工作来做这个……;)
-
哇哦。这真的很糟糕,因为这似乎是一个疯狂的问题。我会看看我能想出什么。
-
如果树是左居中的,这个问题和正常情况下的列表和交换操作有什么区别?
-
非常感谢,我真的很感激!
标签: algorithm binary-tree permutation