Binary Search Albero Traversal - il preorder

voti
8

Io sto cercando di implementare Albero attraversamento in preordine utilizzando dei rendimenti che restituisce 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;
    }

}

In questo caso, va in loop infinito e sì lo so che ho bisogno di tenere traslazione. Come si può fare?

Se il LeftChild o RightChild è nullo, genera un'eccezione null. Credo che a quel punto ho bisogno di cedere break;

Presumo, simmetrico e postorder sarebbe simile anche, tutte le idee?

Ho la versione Resursive, che funziona bene.

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);
    }
}

Grazie.

È pubblicato 04/06/2011 alle 03:34
fonte dall'utente
In altre lingue...                            


1 risposte

voti
4

Opzione # 1 ricorsiva

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);

metodo statico Opzione # 2 non ricorsivo

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);
    }
}
Risposto il 04/06/2011 a 04:04
fonte dall'utente

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