剑指 Offer 27. 二叉树的镜像
题目
代码
/**
* 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:
TreeNode* mirrorTree(TreeNode* root) {
//递归
if(root == nullptr) {
return nullptr;
}
//交换左右子树
TreeNode* temp = root->right;
root->right = mirrorTree(root->left);
root->left = mirrorTree(temp);
return root;
}
};
剑指 Offer 28. 对称的二叉树
题目
代码
法一:递归
/**
* 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 check(TreeNode* p, TreeNode* q) {
if(p == nullptr && q == nullptr) {
return true;
}
if(p == nullptr || q == nullptr) {
return false;
}
//不要忽略p->val == q->val
return (p->val == q->val)&&check(p->right,q->left)&&check(p->left,q->right) ;
}
bool isSymmetric(TreeNode* root) {
//递归
return check(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:
bool check(TreeNode* a,TreeNode* b) {
queue<TreeNode*>q;
q.push(a);
q.push(b);
while(!q.empty()) {
TreeNode* nodea = q.front();
q.pop();
TreeNode* nodeb = q.front();
q.pop();
if(! nodea && !nodeb) {
continue;
}
if(!nodea || !nodeb || (nodea->val != nodeb->val)) {
return false;
}
//nodea->left要与nodeb->right对应
q.push(nodea->left);
q.push(nodeb->right);
q.push(nodea->right);
q.push(nodeb->left);
}
return true;
}
bool isSymmetric(TreeNode* root) {
return check(root, root);
}
};