public IList<IList<int>> LevelOrder()
{
IList<IList<int>> result = new List<IList<int>>();
if (this.Root == null)
{
return result;
}
Queue<BinaryTreeNode> queue = new Queue<BinaryTreeNode>();
queue.Enqueue(this.Root);
while(queue.Count != 0)
{
List<int> currRow = new List<int>();
int rowSize = queue.Count;
while (rowSize > 0)
{
BinaryTreeNode node = queue.Dequeue();
currRow.Add(node.Value);
if (node.LeftNode != null)
{
queue.Enqueue(node.LeftNode);
}
if (node.RightNode != null)
{
queue.Enqueue(node.RightNode);
}
--rowSize;
}
result.Add(currRow);
}
return result;
}
No comments:
Post a Comment