【问题标题】:Implementing a linked list containing all the nodes of each depth of a binary search tree实现一个包含二叉搜索树每个深度的所有节点的链表
【发布时间】: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


    【解决方案1】:

    这是一个想法:

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

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2012-10-10
      • 1970-01-01
      • 2015-05-01
      • 1970-01-01
      • 2021-01-15
      • 1970-01-01
      • 2021-01-02
      相关资源
      最近更新 更多