题目描述
请实现一个函数,用来判断一颗二叉树是不是对称的。注意,如果一个二叉树同此二叉树的镜像是同样的,定义其为对称的。
/*
struct TreeNode {
int val;
struct TreeNode *left;
struct TreeNode *right;
TreeNode(int x) :
val(x), left(NULL), right(NULL) {
}
};
*/
class Solution {
public:
bool isSymmetrical(TreeNode* pRoot)
{
}
};
/思路:首先根节点以及其左右子树,左子树的左子树和右子树的右子树相同, 左子树的右子树和右子树的左子树相同即可,采用递归/
class Solution {
public:
bool isSymmetrical(TreeNode* pRoot)
{
return isSame(pRoot, pRoot);
}
bool isSame(TreeNode *pLeft, TreeNode *pRight)
{
if(pLeft == NULL && pRight == NULL)
return true;
if(pLeft == NULL || pRight == NULL)
return false;
if(pLeft->val != pRight->val)
return false;
return isSame(pLeft->left, pRight->right) && isSame(pLeft->right, pRight->left);
}
};
非递归算法:
使用stack来保存成对的结点;
出栈的时候也是成对成对的,若都为空,继续;一个为空,返回false; 不为空,比较当前值,值不等,返回false。
入栈都是成对入栈的。
class Solution {
public:
bool isSymmetrical(TreeNode* pRoot)
{
if(pRoot == NULL)
{
return true;
}
stack<TreeNode *> sta;
sta.push(pRoot->left);
sta.push(pRoot->right);
while(!sta.empty())
{
TreeNode *right = sta.top();
sta.pop();
TreeNode *left = sta.top();
sta.pop();
if(left == NULL && right == NULL)
continue;
if(left == NULL || right == NULL)
return false;
if(left->val != right->val)
return false;
sta.push(left->left); //成对入栈的
sta.push(right->right);
sta.push(left->right);
sta.push(right->left);
}
return true;
}
};