# C++ 4ms Two solutions: itertive level by level (with two vectors) and recursive

• ``````bool isSymmetric(TreeNode* root)
{
if(!root)
return true;

return isSymmetricRec(root->left, root->right);
}

bool isSymmetricRec(TreeNode* left, TreeNode* right)
{
if(!left && !right)
return true;

if(!left || !right)
return false;

if(left->val != right->val)
return false;

bool outerPairIsSym = isSymmetricRec(left->left, right->right);
bool innerPairIsSym = isSymmetricRec(left->right, right->left);
return outerPairIsSym && innerPairIsSym;
}

bool isSymmetric_Iter2Vectors(TreeNode* root)
{
if(!root)
return true;

vector<TreeNode*> line1, line2, * curLine = &line1, *nextLine = &line2;;
curLine->push_back(root->left);
curLine->push_back(root->right);
while(!curLine->empty())
{
int lineLen = curLine->size();
for(int l = 0, r = lineLen - 1; l < r; ++l, --r)
{
if(!(*curLine)[l] && !(*curLine)[r])
continue;
if(!(*curLine)[l] || !(*curLine)[r])
return false;
if((*curLine)[l]->val != (*curLine)[r]->val)
return false;
}

for(int i = 0; i < lineLen; ++i)
{
if((*curLine)[i])
{
nextLine->push_back((*curLine)[i]->left);
nextLine->push_back((*curLine)[i]->right);
}
}
curLine->clear();
vector<TreeNode*> * tmpCur = curLine;
curLine = nextLine;
nextLine = tmpCur;
}
return true;
}``````

Looks like your connection to LeetCode Discuss was lost, please wait while we try to reconnect.