【发布时间】:2015-05-09 10:03:16
【问题描述】:
我要解决的破解编码面试问题 “给定一棵二叉搜索树,设计一个算法,在每个深度创建一个所有节点的链表(即,如果你有一棵深度为 D 的树,你将有 D 个链表)。”
我很好奇我将如何实现一个链表来显示我一直在处理的当前代码的深度?
class Program
{
static void Main(string[] args)
{
BinarySearchTree bst = new BinarySearchTree();
object[] arr = { 50, 30, 55, 25, 35, 52, 60, 10, 32, 37, 65, 15 };
bst.AddRange(arr);
int level = 1;
string nodeValues = FindNodeValuesAtLevel(bst.Root, level);
Console.WriteLine("Nodes at level " + level + ": " + nodeValues);
Console.Read();
}
static string FindNodeValuesAtLevel(BSTNode root, int level)
{
StringBuilder nodeValuesAtLevel = new StringBuilder();
RM_FindNodeValuesAtLevel(root, level, 0, nodeValuesAtLevel);
return nodeValuesAtLevel.ToString();
}
static void RM_FindNodeValuesAtLevel(BSTNode node, int targetLevel, int curLevel, StringBuilder itemsAtLevel)
{
if (node == null) // stopping condition
return;
else // recursive step
{
// get node value at the target level
if (curLevel == targetLevel)
{
itemsAtLevel.Append(node.NodeValue + " ");
}
// traverse the left node at the next level
RM_FindNodeValuesAtLevel(node.Left, targetLevel, curLevel + 1, itemsAtLevel);
// traverse the right node at the next level
RM_FindNodeValuesAtLevel(node.Right, targetLevel, curLevel + 1, itemsAtLevel);
}
}
}
【问题讨论】:
标签: c# linked-list binary-search-tree