Structurally identical
Given two generic trees, return true if they are structurally identical. Otherwise return false.
Structural Identical
Input format :
Output format :
Constraints:
Sample Input 1 :
Sample Output 1 :
Following is the structure for the TreeNode class
template <typename T>
class TreeNode {
public:
T data;
vector<TreeNode<T>*> children;
TreeNode(T data) {
this->data = data;
}
~TreeNode() {
for (int i = 0; i < children.size(); i++) {
delete children[i];
}
}
};
************************************************************/
bool areIdentical(TreeNode<int> *root1, TreeNode<int> * root2) {
// Write your code here
bool p;
if(root1==NULL&&root2==NULL)
{
return true;
}
else if((root1!=NULL&&root2==NULL)||(root2!=NULL&&root1==NULL))
{
return false;
}
if(root1->data==root2->data)
{
if(root1->children.size()==root2->children.size())
{
if(root1->children.size()==0)
{
return true;
}
for(int i=0;i<root1->children.size();i++)
{
if(root1->children[i]->data!=root2->children[i]->data)
{
return false;
}
}
for(int i=0;i<root1->children.size();i++)
{
p=areIdentical(root1->children[i],root2->children[i]);
}
}
else
{
return false;
}
}
else
{
return false;
}
return p;
}
Comments
Post a Comment