Árbol de búsqueda binaria Transversal - preorden

votos
8

Yo estoy tratando de poner en práctica Árbol recorrido en preorden usando retorno rendimiento que devuelve un IEnumerable

private IEnumerable<T> Preorder(Node<T> node)
{

    while(node != null)
    {
        yield return node.Data;
        yield return node.LeftChild.Data;
        yield return node.RightChild.Data;
    }

}

En este caso, se entra en un bucle infinito y sí sé que tengo que mantener desplazamiento. ¿Cómo puede hacerse esto?

Si el LeftChild o RightChild es nula, emitirá una excepción nula. Creo que en ese punto que necesito dar descanso;

Asumo, a finde y orden posterior serían similares también, alguna idea?

Tengo la versión Resursive, que funciona bien.

public void PreOrderTraversal(Node<T> node)
{

    if(node!=null)
    {
        Console.Write(node.Data);
    }
    if (node.LeftChild != null)
    {
        PreOrderTraversal(node.LeftChild);
    }

    if (node.RightChild != null)
    {
        PreOrderTraversal(node.RightChild);
    }
}

Gracias.

Publicado el 04/06/2011 a las 03:34
fuente por usuario
En otros idiomas...                            


1 respuestas

votos
4

Opción # 1 recursiva

public class Node<T> : IEnumerable<T>
{
    public Node<T> LeftChild { get; set; }

    public Node<T> RightChild { get; set; }

    public T Data { get; set; }

    public IEnumerator<T> GetEnumerator()
    {
        yield return Data;

        if (LeftChild != null)
        {
            foreach (var child in LeftChild)
                yield return child;
        }
        if (RightChild != null)
        {
            foreach (var child in RightChild)
                yield return child;
        }
    }

    System.Collections.IEnumerator System.Collections.IEnumerable.GetEnumerator()
    {
        return GetEnumerator();
    }
}

Uso:

var child1 = new Node<int> { Data = 1 };
var child2 = new Node<int> { Data = 2 };
var child3 = new Node<int> { Data = 3, LeftChild = child1 };
var root = new Node<int> { Data = 4, LeftChild = child3, RightChild = child2 };

foreach (var value in root)
    Console.WriteLine(value);

método estático Opción # 2 no recursiva

public static IEnumerable<T> Preorder<T>(Node<T> root)
{
    var stack = new Stack<Node<T>>();
    stack.Push(root);

    while (stack.Count > 0)
    {
        var node = stack.Pop();
        yield return node.Data;
        if (node.RightChild != null)
            stack.Push(node.RightChild);
        if (node.LeftChild != null)
            stack.Push(node.LeftChild);
    }
}
Respondida el 04/06/2011 a las 04:04
fuente por usuario

Cookies help us deliver our services. By using our services, you agree to our use of cookies. Learn more