Breadth-first traversal

前端 未结 3 2028
无人及你
无人及你 2020-12-13 00:07

I was trying to solve one interview question, but for that I have to travel the binary tree level by level. I have designed BinaryNode with having below variable

         


        
3条回答
  •  轮回少年
    2020-12-13 00:33

    A breadth first search is usually implemented with a queue, a depth first search using a stack.

    Queue q = new Queue();
    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);
    }
    

    As an alternative to checking for null after dequeuing you can check before adding to the Queue. I didn't compile the code, so it might contain some small mistakes.


    A fancier (but slower) version that integrates well with LINQ:

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

    Which can be used together with a Children property on Node:

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

    ...

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

提交回复
热议问题