PDA

View Full Version : سوال: در تابع اینزرت یا درج در یک درخت StackOverflowException



soroush68
یک شنبه 16 فروردین 1388, 10:01 صبح
در این برنامه ی ساده ی درخت در تابع insert این مشکل پیش میاد. توجهتون رو به پیاده سازی تابع CompareTo() در کلاس tree هم جلب می کنم.
ممنون میشم اگر کسی علت این مشکل رو بهم بگه
این برنامه رو از لینک زیر میتونید دانلود کنید
http://soroushweb.persiangig.com/BinaryTree-f.rar

soroush68
یک شنبه 16 فروردین 1388, 11:07 صبح
در فروم ام اس دن مایکروسافت اینطور مساله حل شد

Now there are two logicall Mistakes I found in your program.

1) In Insert Method


if (CompareTo(NewItem) > 0)
{
if (this.LefTree == null)
this.LefTree = new Tree<TItem>(NewItem);
else
this.Insert(NewItem); //// calling insert method on same node you called earlier

}
else
{
if (this.RightTree == null)
this.RightTree = new Tree<TItem>(NewItem);
else
this.Insert(NewItem); // calling insert method on same node you called earlier
}


Now you can see clearly when LeftTree or RightTree is not null, hence the else block will execute, Then Insert method is called on the same Node. I must be this.LeftTree.Insert(NewItem);


if (CompareTo(NewItem) > 0)
{
if (this.LefTree == null)
this.LefTree = new Tree<TItem>(NewItem);
else
this.LefTree.Insert(NewItem);
}
else
{
if (this.RightTree == null)
this.RightTree = new Tree<TItem>(NewItem);
else
this.RightTree.Insert(NewItem);
}

In this way, When the LefTree exists you will call Insert method on that. Got the point?

2) In Walk Tree Method

Again you are doing same mistake in the walk tree method. When the left or right tree is not null, You are calling walktree on same node instead of calling it on left or right node.