الفريق العربي للبرمجةأرشيف المنتديات · 2000 – 2023
نسخة أرشيفية للقراءة فقط — التسجيل والمشاركة مغلقان، والمحتوى محفوظ كما كان.

Avl Tree ... Generation Function

بدأه albronzy في 6 مارس 2008 · 1 رد · 707 مشاهدة · في الأسئلة المجابة
مشاركة: واتساب X فيسبوك تيليجرام
#1 صاحب الموضوع

alsalaam 3likom

I'm not sure if this code is correct or not.

could you please help me to make sure if it is right or not.

I want to generate AVL tree function of height h with fewest nodes.

here is the code

template <class Comparable>
void AvlTree<Comparable>::generate( const Comparable & h, AvlNode<Comparable> * & t )
{
if( t == NULL )
t = new AvlNode<Comparable>( "", NULL, NULL);
else {if( height( t->left ) < height( t->right ) )
insert( t->left )
else if( height( t->left ) > height( t->right ) )
insert( t->right );
else
if( height( t->left ) == height( t->right ) )
insert( t->left );

t->height = max( height( t->left ), height( t->right ) ) + 1;
if (height!=h)
generate(h,t)

}

تم تعديل هذه المشاركة بواسطة albronzy في 6 مارس 2008 في 09:45

#2
template <class Comparable>
void AvlTree<Comparable>::generate( const Comparable & h, AvlNode<Comparable> * & t )
{

if( t == NULL )
	t = new AvlNode<Comparable>( "", NULL, NULL);

else{
	 // It's more correct to check before you insert new nodes, as 't' could initially be of height 'h'
	 t->height = max( height( t->left ), height( t->right ) ) + 1;
	 if (t->height==h)
		   return;

	// I think this is more appropriate>
	if( height( t->left ) <= height( t->right ) )
		 insert( t->left )
	else
		insert( t->right );
}

generate(h,t);
}

LEFT TO RIGHT
I made some "minor" modifications which, I think, would make the code look more elegant. Also I think this is not a very good application of recursion, as you pass the same arguments to the generate() function each time! I guess it'll be more naturally done via looping.

مواضيع مشابهة