题目描述:
请实现一个函数,用来判断一棵二叉树是不是对称的。注意,如果一个二叉树同此二叉树的镜像是同样的,定义其为对称的。
题解:
class Solution {
public:
bool isSymmetrical(TreeNode* pRoot)
{
if(pRoot == NULL)
return true;
queue<TreeNode*> que;
que.push(pRoot->left);
que.push(pRoot->right);
while(!que.empty())
{
TreeNode* t1 = que.front();
que.pop();
TreeNode* t2 = que.front();
que.pop();
if(t1==NULL && t2 == NULL)
continue;
if(t1 == NULL || t2 == NULL)
return false;
if(t1->val != t2->val)
return false;
que.push(t1->left);
que.push(t2->right);
que.push(t1->right);
que.push(t2->left);
}
return true;
}
};
解题思路:
利用二叉树的层序遍历,每次比较两个节点,但是这两个节点是对称的。注意在入队列的时候也要让两个对称的节点先后入队列。