黑马程序员—C#中递归

来源:互联网 发布:下载国泰安数据 编辑:程序博客网 时间:2024/06/05 23:41
------- Windows Phone 7手机开发、.Net培训、期待与您交流! -------


 //递归求 1 1 2 3 5 8

用递归前


      static void Main(string[] args)
        {
            //递归求 1 1 2 3 5 8
            int[] num = new int[10];
            num[0] = 1;
            num[1] = 1;
            for (int i = 2; i < num.Length; i++)
            {
                num[i] = num[i-1] + num[i-2];
             
            }
            Console.WriteLine(num[9]);
           }


用递归

      static void Main(string[] args)
        {
           
            Console.WriteLine(DiGui(10));
            Console.ReadLine();      
        }
        //递归
        public static int DiGui(int i)
        {
            if (i==1)
            {
                return 1;
            }
            else if (i==2)
            {
                return 1;
            }
            else
            {
                return DiGui(i - 1) + DiGui(i - 2);
            }
           
        }



资料管理器  递归案例

  private void Form1_Load(object sender, EventArgs e)        {            CreateParent();//加载文件        }        void CreateParent()        {            tvType.Nodes.Clear();  //清空 Treeview            string path = "我的文件夹";            TreeNode tn = new TreeNode();            tn.Text = path;            tvType.Nodes.Add(tn);            CreateChild(path, tn);  //加载目录下的文件夹            CreateFile(path, tn);   //加载目录下的文件            tvType.ExpandAll();     //展开所有节点            //tvType.CollapseAll();   //折叠所有节点        }        void CreateChild(string path, TreeNode parent)        {            string[] dr = Directory.GetDirectories(path);            foreach (string  item in dr)            {                TreeNode child = new TreeNode();                child.Text = Path.GetFileNameWithoutExtension(item);  //文件名                child.Tag = item;    //文件夹全路径                parent.Nodes.Add(child);   //将子节点添加到父节点                CreateFile(item ,child);   //遍历目录下的文件                CreateChild(item, child);  //用递归遍历目录下的目录            }        }        private void CreateFile(string path, TreeNode parent)        {            string[] files = Directory.GetFiles(path,"*.txt");            foreach (string item in files)            {                TreeNode child = new TreeNode();                child.Text = Path.GetFileName(item);  //文件名                child.Tag = item;  //文件全路径                parent.Nodes.Add(child);            }        }        //当选项改变时        private void tvType_AfterSelect(object sender, TreeViewEventArgs e)        {            if (e.Node .Tag ==null)            {                return;            }            string path = e.Node.Tag.ToString();//获取文件全路径            txtTitle.Text = Path.GetFileNameWithoutExtension(path);  //获取文件名            txtContent.Text = File.ReadAllText(path, Encoding.GetEncoding("gb2312"));   //读取文件内容                    }