I am trying to solve the given problem using Breadth-first Search (I know Depth-first search will be best suited for this scenario but I just want to try out things)
My code seems to be working in case of other test-cases but fails in case of first test case. Please suggest some improvements in my code.
Problem Link - https://leetcode.com/problems/leaf-similar-trees/
My Code:
/**
* Definition for a binary tree node.
* struct TreeNode {
* int val;
* TreeNode *left;
* TreeNode *right;
* TreeNode() : val(0), left(nullptr), right(nullptr) {}
* TreeNode(int x) : val(x), left(nullptr), right(nullptr) {}
* TreeNode(int x, TreeNode *left, TreeNode *right) : val(x), left(left), right(right) {}
* };
*/
class Solution {
public:
bool leafSimilar(TreeNode* root1, TreeNode* root2) {
vector<int> v1, v2;
queue<TreeNode*> q1;
queue<TreeNode*> q2;
//Applying BFS for first tree
q1.push(root1);
while(!q1.empty())
{
int size = q1.size();
for(int i=0;i<size;i++)
{
TreeNode* curr = q1.front();
q1.pop();
if(curr->left != NULL)
q1.push(curr->left);
if(curr->right != NULL)
q1.push(curr->right);
if(curr->left == NULL && curr->right == NULL)
v1.push_back(curr->val);
}
}
//Applying BFS for second tree
q2.push(root2);
while(!q2.empty())
{
int size = q2.size();
for(int i=0;i<size;i++)
{
TreeNode* curr = q2.front();
q2.pop();
if(curr->left != NULL)
q2.push(curr->left);
if(curr->right != NULL)
q2.push(curr->right);
if(curr->left == NULL && curr->right == NULL)
v2.push_back(curr->val);
}
}
if(v1.size() != v2.size())
return false;
for(int i=0;i<v1.size();i++)
{
if(v1[i] != v2[i])
return false;
}
return true;
}
};