【问题标题】:Breadth-first traversal广度优先遍历
【发布时间】:2018-01-23 21:51:46
【问题描述】:

我试图解决一个面试问题,但为此我必须逐级遍历二叉树。我设计了具有以下变量的 BinaryNode

private object data;
private BinaryNode left;
private BinaryNode right;

有人可以帮忙在我的 BinarySearchTree 类中编写 BreadthFirstSearch 方法吗?

更新:感谢大家的投入。所以这是面试问题。 “给定一个二叉搜索树,设计一个算法,在每个深度创建一个所有节点的链表(即,如果你有一个深度为 D 的树,你将有 D 个链表)”。

这是我的方法,让我知道您的专家意见。

public List<LinkedList<BNode>> FindLevelLinkList(BNode root)
    {
        Queue<BNode> q = new Queue<BNode>();
        // List of all nodes starting from root.
        List<BNode> list = new List<BNode>();
        q.Enqueue(root);
        while (q.Count > 0)
        {
            BNode current = q.Dequeue();
            if (current == null)
                continue;
            q.Enqueue(current.Left);
            q.Enqueue(current.Right);
            list.Add(current);
        }

        // Add tree nodes of same depth into individual LinkedList. Then add all LinkedList into a List
        LinkedList<BNode> LL = new LinkedList<BNode>();
        List<LinkedList<BNode>> result = new List<LinkedList<BNode>>();
        LL.AddLast(root);
        int currentDepth = 0;
        foreach (BNode node in list)
        {
           if (node != root)
            {
                if (node.Depth == currentDepth)
                {
                    LL.AddLast(node);
                }
                else
                {
                    result.Add(LL);
                    LL = new LinkedList<BNode>();
                    LL.AddLast(node);
                    currentDepth++;
                }
            }
        }

        // Add the last linkedlist
        result.Add(LL);
        return result;
    }

【问题讨论】:

标签: c# .net algorithm data-structures


【解决方案1】:

广度优先搜索通常使用队列实现,深度优先搜索使用堆栈

Queue<Node> q = new Queue<Node>();
q.Enqueue(root);
while(q.Count > 0)
{
    Node current = q.Dequeue();
    if(current == null)
        continue;
    q.Enqueue(current.Left);
    q.Enqueue(current.Right);

    DoSomething(current);
}

作为在出队后检查null 的替代方法,您可以在添加到队列之前检查。我没有编译代码,所以它可能包含一些小错误。


与 LINQ 完美集成的更高级(但速度较慢)的版本:

public static IEnumerable<T> BreadthFirstTopDownTraversal<T>(T root, Func<T, IEnumerable<T>> children)
{
    var q = new Queue<T>();
    q.Enqueue(root);
    while (q.Count > 0)
    {
        T current = q.Dequeue();
        yield return current;
        foreach (var child in children(current))
            q.Enqueue(child);
    }
}

它可以与Node 上的Children 属性一起使用:

IEnumerable<Node> Children { get { return new []{ Left, Right }.Where(x => x != null); } }

...

foreach(var node in BreadthFirstTopDownTraversal(root, node => node.Children))
{
   ...
}

【讨论】:

  • @Via 并不奇怪。队列是实现广度优先搜索的明显选择,就像您使用堆栈作为深度优先一样。
  • @CodeInChaos 感谢您的帮助。虽然这是一篇旧帖子,但我想我会留下反馈以防它对某人有所帮助。 1)我无法编译您的“更高级的解决方案”。 2)您原来的解决方案效果很好。再次感谢。
  • 对 DFS 和 BFS 进行了很好的比较,我了解 DFS 但我就是无法获得 BFS,所以这个问题的关键是使用队列而不是堆栈。谢谢。
【解决方案2】:
var queue = new Queue<BinaryNode>();
queue.Enqueue(rootNode);

while(queue.Any())
{
  var currentNode = queue.Dequeue();
  if(currentNode.data == searchedData)
  {
    break;
  }

  if(currentNode.Left != null)
    queue.Enqueue(currentNode.Left);

  if(currentNode.Right != null)
    queue.Enqueue(currentNode.Right);
}

【讨论】:

  • 这可能是一个愚蠢的建议,但您可以将两个if 条件替换为一个在匹配searchedData 之前检查null 的条件;即使它只是少了 1 行 xD
【解决方案3】:

使用 DFS 方法:树的遍历是 O(n)

public class NodeLevel
{
    public TreeNode Node { get; set;}
    public int Level { get; set;}
}

public class NodeLevelList
{
    private Dictionary<int,List<TreeNode>> finalLists = new Dictionary<int,List<TreeNode>>();

    public void AddToDictionary(NodeLevel ndlvl)
    {
        if(finalLists.ContainsKey(ndlvl.Level))
        {
            finalLists[ndlvl.Level].Add(ndlvl.Node);
        }
        else
        {
            finalLists.Add(ndlvl.Level,new List<TreeNode>(){ndlvl.Node});
        }
    }

    public Dictionary<int,List<TreeNode>> GetFinalList()
    {
        return finalLists;
    }
}

遍历的方法:

public static void DFSLevel(TreeNode root, int level, NodeLevelList nodeLevelList)
{
    if(root == null)
        return;

    nodeLevelList.AddToDictionary(new NodeLevel{Node = root, Level = level});

    level++;

    DFSLevel(root.Left,level,nodeLevelList);
    DFSLevel(root.Right,level,nodeLevelList);

}

【讨论】:

  • 如果您可以添加评论以反对投票,那会很有帮助
  • 一个很好的猜测是 OP 要求广度优先,而你的开场白说你的答案是深度优先。
  • 另外,你基本上通过创建字典和许多列表来分配比需要更多的内存,如果你所做的只是搜索特定值,那么这些列表并不是真正需要的
猜你喜欢
  • 1970-01-01
  • 2019-08-10
  • 1970-01-01
  • 2016-02-15
  • 2011-07-12
  • 2015-06-10
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多