实现包含二叉搜索树的每个深度的所有节点的链表

时间:2015-05-09 10:03:16

标签: c# linked-list binary-search-tree

我要解决破解编码面试的问题 “给定一个二叉搜索树,设计一个算法,创建每个深度的所有节点的链表(即,如果你有一个深度为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);

        }
    }

}

1 个答案:

答案 0 :(得分:0)

这是一个想法:

按顺序遍历树。由于您知道何时下降到子树,因此您可以简单地跟踪您正在访问的每个节点的高度。对于您访问的高度为k的每个节点,将其添加到链接列表k。如果您还没有高度k的链接列表,请创建一个空列表并将其添加到链接列表的列表/数组中。