Assignment
Solution Change it according to your university
requirement before submitting #include
<stdlib.h> #include <iostream> using namespace std; template
<class Object>
class
TreeNode {
public:
TreeNode() {
this->object = NULL;
this->left =
this->right = NULL;
};
TreeNode( Object *
object ) { this->object = object;
this->left =
this->right = NULL;
};
Object
* getInfo()
{
return
this->object;
};
void
setInfo(Object * object) {
this->object = object;
TreeNode
* getLeft() {
return left;
};
void
setLeft(TreeNode * left)
{
this->left = left;
};
TreeNode
* getRight()
{
return
right;
};
void
setRight(TreeNode * right)
{
this->right = right;
};
int isLeaf( )
{
if(
this->left == NULL && this->right == NULL )
return
1;
return
0;
};
private:
Object * object;
TreeNode
* left;
TreeNode
* right;
};
void
insert (TreeNode <int> * root, int * info)
{
TreeNode
<int> * node = new TreeNode <int> (info);
TreeNode <int> * p, *
q;
p = q
= root;
while( *info !=
*(p->getInfo()) && q != NULL )
{
p =
q;
if(
*info < *(p->getInfo()) )
q =
p->getLeft(); else
q =
p->getRight();
}
if(
*info == *( p->getInfo() ) )
{
cout << "attempt
to insert duplicate: " << *info ;
delete
node;
}
else if( *info <
*(p->getInfo()) )
p->setLeft( node );
else
p->setRight( node );
} //
end of insert
{
if (root == NULL)
return 0;
if (*(root->getInfo()) == data)
return level;
int downlevel =
getNodeLevel(root->getLeft(), data, level+1);
if (downlevel != 0)
return downlevel;
downlevel = getNodeLevel(root->getRight(), data, level+1);
return downlevel;
}
void printGivenRow(TreeNode<int>* root, int level)
{
if(root == NULL)
return;
if(level == 1)
cout << *(root->getInfo())<<" ";
else if (level > 1)
{
printGivenRow(root->getLeft(), level-1);
printGivenRow(root->getRight(), level-1);
}
}
int
height(TreeNode<int>* node)
if
(node==NULL)
return
0;
else
{
/*
compute the height of each subtree */
int
lheight = height(node->getLeft());
int
rheight = height(node->getRight());
/* use the larger one */ if
(lheight > rheight) return(lheight+1); else return(rheight+1);
}
}
void
printRow(TreeNode<int>* root)
int h
= height(root);
int
i;
for(i=1;
i<=h; i++){
cout<<"At Row
"<<i-1<< " :"; printGivenRow(root, i);
cout<<endl;
void carInfo(TreeNode<int>* root)
{
int h = height(root);
int
i;
for(i=1;
i<=h; i++){
cout<<"Car
";
printGivenRow(root,
i); cout<<endl;
}
}
/*
Returns level of given data value */
int
getLevel(TreeNode<int>* node, int data)
{
return getNodeLevel(node,data,1);
}
int
main(int argc, char * argv[])
{
int
x[] = {14, 15, 4, 9, 7, 18, 3, 5, 16, 20, 17};
TreeNode
<int> * root = new TreeNode<int>();
root->setInfo( &x[0]
);
for(int
i = 1; x[i] > 0; i++ )
{
insert(
root, &x[i] );
}
int i
=0;
for (i = 0; i <=10;
i++)
{
int
data = x[i];
int
level = getLevel(root, data);
if (level)
cout<<" Car
"<< data <<" is at Row : "<< (getLevel(root,
data)-1)<<endl;
}
cout<<endl;
printRow(root);
}
Compiled Result