方法1:队列迭代
方法2:递归
队列迭代:
class Solution {
public:
TreeNode* mirrorTree(TreeNode* root) {
queue<TreeNode*> q;
if(root==NULL) return root;
q.push(root);
while(!q.empty())
{
TreeNode *cur=q.front();
if(!cur) continue;//不要忘记谢谢
swap(cur->left,cur->right);
q.pop();
if(cur->left) q.push(cur->left);
if(cur->right) q.push(cur->right);
}
return root;
}
};
递归
class Solution {
public:
TreeNode* mirrorTree(TreeNode* root) {
queue<TreeNode*> q;
if(root==NULL) return root;
swap(root->left,root->right);
mirrorTree(root->left);
mirrorTree(root->right);
return root;
}
};
基于上面的基础,我看看对称后的树是不是和当前树一样
先递归
class Solution {
public:
bool DFSSymmetric(TreeNode* A,TreeNode* B)
{
if(!A&&!B) return true;
else if(A&&B)
{
return (A->val==B->val)&&DFSSymmetric(A->left,B->right)&&(DFSSymmetric(A->right,B->left));}
else return false;
}
bool isSymmetric(TreeNode* root)
{
if(root==NULL) return true;
return DFSSymmetric(root->left,root->right);
}
};
队列迭代
class Solution {
public:
bool Symmetric(TreeNode* A,TreeNode* B)
{
queue<TreeNode*> q;
q.push(A),q.push(B);
while(!q.empty())
{
TreeNode *a=q.front();
q.pop();
TreeNode *b=q.front();
q.pop();
if (!a && !b) continue;
if ((!a || !b) || (a->val != b->val)) return false;
q.push(a->left); //前面已经判断完a b为空的情况 到这边a,b肯定不为空,至于左孩子右孩子最不济也是null
q.push(b->right);
q.push(a->right);
q.push(b->left);
}
return 1;
}
bool isSymmetric(TreeNode* root)
{
if(root==NULL) return true;
return Symmetric(root->left,root->right);
}
};
递归 注意边界条件
class Solution {
public:
bool SubStructure(TreeNode* A, TreeNode* B)
{
if(!B) return 1;//结束条件1,B最后一个遍历完了
if(!A||A->val!=B->val) return 0;
return SubStructure(A->left,B->left)&&SubStructure(A->right,B->right);
}
bool isSubStructure(TreeNode* A, TreeNode* B) {
if(!A||!B) return 0;//其中一个存在
// 根节点相同直接比较,根节点不同看B是不是A的左右子树结构
return SubStructure(A,B)||isSubStructure(A->left,B)||isSubStructure(A->right,B);
}
};