【发布时间】:2014-12-03 01:01:39
【问题描述】:
我正在寻找一种更好或更优化的方法来复制(或在实际问题中,转换)n 叉树 使用递归。关于我试图解决的一般情况的一些细节如下
- 树是 n 元的(即,每层最多 n 个节点)
- 孩子有到父母的链接,父母有所有孩子的列表
- 在树的任何给定级别中,任何节点都可以是叶子或分支
我想出了以下解决方案。一般的方法是使用两(三)个堆栈。第一个跟踪原始树中需要处理的项目,第二个跟踪新创建的副本,以便我们可以适当地分配节点之间的链接(这可以分为两个堆栈而不是元组,因此三个)。这可行,但它有许多不受欢迎的方面,首先是感觉非常尴尬。我认为必须有更好的方法来做到这一点,但我遗漏了一些(或多个)明显的东西。
有没有人遇到过更直接/更有效的方法?
public TreeNode ConvertTree(TreeNode root)
{
Stack<TreeNode> processingStack = new Stack<TreeNode>();
Stack<Tuple<Int32, TreeNode>> resultStack = new Stack<Tuple<Int32, TreeNode>>();
TreeNode result = null;
processingStack.Push(root);
while (processingStack.Count > 0)
{
var currentProcessingNode = processingStack.Pop();
var parentNode = resultStack.Count > 0 ? resultStack.Pop() : null;
// Copies all leaf nodes and assigns parent, if applicable.
var newResultNode = CopyNodeData(currentProcessingNode, parentNode != null ? parentNode.Item2 : null);
// Push sub-branch nodes onto the processing stack, and keep track of how many for
// each level.
var subContainerCount = 0;
foreach (var subContainer in currentProcessingNode.Children.Where(c => !c.IsLeaf))
{
processingStack.Push(subContainer);
subContainerCount++;
}
// If we have have not processed all children in this parent, push it back on and
// decrement the counter to keep track of it.
if (parentNode != null && parentNode.Item1 > 1)
{
resultStack.Push(new Tuple<Int32, TreeNode>(parentNode.Item1 - 1, parentNode.Item2));
}
// If this node has sub-branches, push the newly copied node onto the result/tracking
// stack
if(subContainerCount > 0)
resultStack.Push(new Tuple<Int32, TreeNode>(subContainerCount, newResultNode));
// The very first time a new node is created, track it to return as the result
if (newResultNode.IsRoot)
result = newResultNode;
}
return result;
}
请注意,我不是在寻找递归解决方案。是的,我意识到它们在许多情况下都是可用的、简单的和适当的。这个问题更多的是关于如何以迭代方式有效地完成这种类型的操作,而不仅仅是如何将其拉下来。
【问题讨论】:
标签: c# data-structures tree tree-traversal