C#Binary Tree's - Inorder/Preorder和PostOrder(递归帮助)

Ste*_*ine 5 c# recursion binary-tree

我需要一些递归帮助.我正在尝试用C#做一个二叉树,我想知道是否有可能用递归函数演示所有Inorder/PostOrder和PreOrder遍历.

我已经为PreOrder完成了它然后尝试了InOrder然而导致了StackOverflow异常,我对Binary Tree的掌握最多是脆弱的,所以任何对此的帮助都会非常感激,即使它看起来像是一个愚蠢的问题.

以下代码是我用于PreOrder Traversal的代码;

     public void recursivePreorder(BinaryTreeNode root)
    {
        Console.Write(root.Data.ToString());
        if (root.Left != null)
        {
            recursivePreorder(root.Left);
        }
        if (root.Right != null)
        {
            recursivePreorder(root.Right);
            }
    }

     public void preorderTraversal()
    {
        if (Root != null)
        {
            recursivePreorder(Root);
        }
        else
        {
            Console.WriteLine("There is no tree to process");
        }

    static void Main(string[] args)
    {

        // Build the tree
        Test.Add(5);
        Test.Add(2);
        Test.Add(1);
        Test.Add(3);
        Test.Add(3); // Duplicates are OK
        Test.Add(4);
        Test.Add(6);
        Test.Add(10);
        Test.Add(7);
        Test.Add(8);
        Test.Add(9);
        // Test if we can find values in the tree

        for (int Lp = 1; Lp <= 10; Lp++)
            Console.WriteLine("Find Student ID ({0}) = {1}", Lp, Test.Find(Lp));

        // Test if we can find a non-existing value
        Console.WriteLine("Find Student ID (999) = {0}", Test.Find(999));

        // Iterate over all members in the tree -- values are returned in sorted order
        foreach (int value in Test)
        {
            Console.WriteLine("Value: {0}", value);
        }

        Console.WriteLine("Preorder Traversal");
        Console.WriteLine("");
        Test.preorderTraversal();
        Console.WriteLine("");
    }
Run Code Online (Sandbox Code Playgroud)

在此先感谢,这绝对是我无法解决的问题,我甚至不确定是否可能.

Bro*_*ass 6

Inorder 与您已有的非常相似,只需在处理当前节点的位置稍微移动代码即可:

public void recursiveInorder(BinaryTreeNode root)
{
    if (root.Left != null)
    {
        recursiveInorder(root.Left);
    }
    Console.Write(root.Data.ToString());
    if (root.Right != null)
    {
        recursiveInorder(root.Right);
    }
}
Run Code Online (Sandbox Code Playgroud)

与 preorder 的区别只是你先遍历左子树,然后处理当前节点,最后遍历右子树。