Symmetric Tree
题记:为了明年的各种笔试面试,现在开始,计划每两天在LeetCode里面AC一个算法题,目前里面有150多个,差不多明年8,9月份能做完,给自己的动力吧。
Given a binary tree, check whether it is a mirror of itself (ie, symmetric around its center).
For example, this binary tree is symmetric:
1 / \ 2 2 / \ / \ 3 4 4 3
But the following is not:
1 / \ 2 2 \ \ 3 3
题目要求尽量用递归、迭代,暂时使用了层次遍历的方式,使用两个队列来保存要比较的各个节点。
bool isSymmetric(TreeNode *root)
{
if(root == NULL)
{
return true;
}
TreeNode* pLeft=root->left, *pRight=root->right;
//把节点集从根节点分开,将根节点的左子树节点保存到qLeft中,右子树节点保存到qRight中
queue<TreeNode*> qLeft, qRight;
qLeft.push(pLeft);
qRight.push(pRight);
//两个队列都不空,层次遍历算法,一层一层对两个队列的元素进行比较
while(qLeft.empty()==false && qRight.empty()==false)
{
pLeft = qLeft.front();
pRight = qRight.front();
if(pLeft!=NULL && pRight!=NULL)
{
if(pLeft->val != pRight->val)
{
return false;
}
else
{
qLeft.pop();
//先入该节点的左子节点,再入右子节点
qLeft.push(pLeft->left); qLeft.push(pLeft->right);
qRight.pop();
//先入该节点的右子节点,再入左子节点
qRight.push(pRight->right); qRight.push(pRight->left);
}
}
else if(pLeft==NULL && pRight==NULL)
{
qLeft.pop();
qRight.pop();
}
else
{
return false;
}
}
if(qLeft.empty()==true && qRight.empty()==true)
{
return true;
}
else
{
return false;
}
}
后续递归、迭代算法再进行补充。。。