【发布时间】:2015-01-11 05:45:31
【问题描述】:
我正在尝试使用队列遍历树中的所有叶节点。 但我无法得到任何输出。
class MyNode<T>
{
public T Data { get; set; }
public MyNode<T> Parent { get; set; }
public List<MyNode<T>> Children = new List<MyNode<T>>();
public MyNode(T data, MyNode<T> parent)
{
Data = data;
Parent = parent;
}
public override string ToString()
{
if (Children == null) return Data.ToString();
return string.Format("{0} {1} ", Data.ToString(), Children.ToString());
}
}
一个节点可以有任意数量的子节点。这是我写的打印所有叶节点的内容。我什么也得不到,我想只有最后一行 Console.WriteLine("");被处决了,但我不知道为什么。
public static void PrintSentence(MyNode<string> root)
{
if (root == null) // Return when the tree is empty.
return;
Queue<MyNode<string>> nodeQueue = new Queue<MyNode<string>>();
nodeQueue.Enqueue(root);
MyNode<string> currentNode = root;
while (nodeQueue.Count != 0)
{
currentNode = nodeQueue.Peek();
nodeQueue.Dequeue();
if (currentNode.Children == null) // Print strings only when the current node is a leaf node.
Console.Write(currentNode.Data + " ");
for (int i = 0; i < currentNode.Children.Count(); i++)
nodeQueue.Enqueue(currentNode.Children[i]);
}
Console.WriteLine("");
}
感谢您的帮助。 树类是这样的,实际上我在任何地方都找不到我的调试窗口...... 我只写了PrintSentence方法,其他的都是别人写的。
class Tree<T>
{
public MyNode<T> Root { get; set; }
public Tree(MyNode<T> root) { Root = root; }
public override string ToString()
{
if (Root == null) return "";
return Root.ToString();
}
}
【问题讨论】:
-
您能否提供更多信息——尤其是您的树?此外,当您在调试器中单步执行代码时,执行了哪些代码,哪些未执行?
标签: c# data-structures