首页 新闻 会员 周边 捐助

关于一个递归的问题

0
悬赏园豆:15 [已关闭问题] 关闭于 2012-08-14 13:19

自己在那里分析了半天,感觉有点晕乎乎的,虽然也分析出来了,但是想看看大家有没有更好的可以借鉴的方法,代码如下

using System;
public class MainClass
{
    static void Main()
    {
        BinarySearchTree nums = new BinarySearchTree();
        nums.Insert(23);
        nums.Insert(45);
        nums.Insert(16);
        nums.Insert(37);
        nums.Insert(3);
        nums.Insert(99);
        nums.Insert(22);
        Console.WriteLine("Inorder traversal: ");
        nums.InOrder(nums.root);
        Console.ReadKey();
    }
}
public class Node
{
    public int Data;
    public Node Left;
    public Node Right;
    public void DisplayNode()
    {
        Console.Write(Data + " ");
    }
}
public class BinarySearchTree
{
    public Node root;
    public BinarySearchTree()
    {
        root = null;
    }
    public void InOrder(Node theRoot)
    {
        if (!(theRoot == null))
        {
            InOrder(theRoot.Left);
            theRoot.DisplayNode();
            InOrder(theRoot.Right);
        }
    }
    public void Insert(int i)
    {
        Node newNode = new Node();
        newNode.Data = i;
        if (root == null)
            root = newNode;
        else
        {
            Node current = root;
            Node parent;
            while (true)
            {
                parent = current;
                if (i < current.Data)
                {
                    current = current.Left;
                    if (current == null)
                    {
                        parent.Left = newNode;
                        break;
                    }
                }
                else
                {
                    current = current.Right;
                    if (current == null)
                    {
                        parent.Right = newNode;
                        break;
                    }
                }
            }
        }
    }
}

主要分析一下InOrder那里的递归,谢谢

微澜的主页 微澜 | 初学一级 | 园豆:-1
提问于:2012-06-07 14:39
< >
分享
清除回答草稿
   您需要登录以后才能回答,未注册用户请先注册