一个树为对称的仅当两棵子树互为镜像,即要满足:
1.子树根节点值相等
2.每个树的右子树都与另一个树的左子树镜像对称。
有递归迭代两种解法:
递归:
/**
* Definition for a binary tree node.
* struct TreeNode {
* int val;
* TreeNode *left;
* TreeNode *right;
* TreeNode(int x) : val(x), left(NULL), right(NULL) {}
* };
*/
class Solution {
public:
bool DFS(TreeNode*root1,TreeNode* root2)
{
if(!root1&&!root2)
return true;
if(!root1||!root2||root1->val!=root2->val)
return false;
return DFS(root1->left,root2->right)&&DFS(root1->right,root2->left);
}
bool isSymmetric(TreeNode* root) {
return DFS(root,root);
}
};
迭代:
/**
* Definition for a binary tree node.
* struct TreeNode {
* int val;
* TreeNode *left;
* TreeNode *right;
* TreeNode(int x) : val(x), left(NULL), right(NULL) {}
* };
*/
class Solution {
public:
queue<TreeNode*>q;
bool check(TreeNode* node1,TreeNode* node2)
{
// if(node1==NULL)return true;
q.push(node1);
q.push(node2);
while(!q.empty())
{
TreeNode* u=q.front();
q.pop();
TreeNode* v=q.front();
q.pop();
if(!u&&!v)continue;
if(!u||!v||u->val!=v->val)
return false;
q.push(u->left);
q.push(v->right);
q.push(u->right);
q.push(v->left);
}
return true;
}
bool isSymmetric(TreeNode* root) {
return check(root,root);
}
};