注册 登录
编程论坛 C# 论坛

这个递归调用,n只等于1

wstcl 发布于 2015-08-31 10:39, 1743 次点击
从某书上的一个实例(网上下载相应代码),一个二叉树的排序,先插入,然后用递归遍历输出,比如插入5个元素,在控制台的确了输出了5个排序后的元素,但我在里面n++;n最后输出只有1,为什么啊
5 回复
#2
wstcl2015-08-31 10:41
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Collections;
namespace BinaryTree
{
    public class Tree<TItem> where TItem : IComparable<TItem>
    {
        public Tree(TItem nodeValue)
        {
            this.NodeData = nodeValue;
            this.LeftTree = null;
            this.RightTree = null;
        }

        public void Insert(TItem newItem)
        {
            TItem currentNodeValue = this.NodeData;
            if ((newItem) > 0)
            {
                if (this.LeftTree == null)
                {
                    this.LeftTree = new Tree<TItem>(newItem);
                }
                else
                {
                    this.LeftTree.Insert(newItem);
                }
            }
            else
            {
                if (this.RightTree == null)
                {
                    this.RightTree = new Tree<TItem>(newItem);
                }
                else
                {
                    this.RightTree.Insert(newItem);
                }
            }
        }

        public void WalkTree()
        {
            if (this.LeftTree != null)
            {
                this.LeftTree.WalkTree();
               
            }

            Console.WriteLine(this.NodeData.ToString());
            n++;//n每递归一次后,又返回到0
            
            if (this.RightTree != null)
            {
                this.RightTree.WalkTree();
            }
        }

        public TItem NodeData { get; set; }
        public Tree<TItem> LeftTree { get; set; }
        public Tree<TItem> RightTree { get; set; }

      
        public int n=0;
    }
}
#3
wstcl2015-08-31 10:41
看看这个代码,为什么啊,我是用c#2010写的。
#4
wstcl2015-08-31 10:55
明白了,因为每递归一次,类就实例化一次,而n是在类中定义的。
#5
米粒大小32015-10-25 16:14
回复 2楼 wstcl
厉害!!!
#6
林月儿2015-10-26 12:44
定义成静态不就好了
1