This question is also a classic question and needs attention. My solution also refers to the answers on the Internet.
Solution 1: Recursion
bool isMirror(TreeNode* r1, TreeNode* r2) {
if (!r1 && !r2) return true;
if (!r1 || !r2) return false;
if (r1->val!=r2->val) return false;
return isMirror(r1->left, r2->right) && isMirror(r1->right, r2->left);
}
bool isSymmetric(TreeNode* root) {
if (!root) return true;
return isMirror(root->left, root->right);
}
Note: You can also use if() in isSymmetric(), but directly return isMirror(root, root). In leetcode, the version without if only takes 8 seconds, and my version takes 9 seconds. I don’t know why it is missing once Is recursion slower?
Solution 2: Iterate. It is similar to traversing the binary tree level.
bool isSymmetric(TreeNode* root) {
queue<TreeNode*> q;
if (!root) return true;
q.push(root->left);
q.push(root->right);
while(!q.empty()) {
TreeNode* p1=q.front(); q.pop();
TreeNode* p2=q.front(); q.pop();
if (!p1 && !p2) continue; //注意这里要返回。
if (!p1 || !p2) return false;
if (p1->val != p2->val) return false;
q.push(p1->left);
q.push(p2->right);
q.push(p1->right);
q.push(p2->left);
}
return true;
}
Note: Some solutions on the Internet here do not check if(!root) at first, but push(root) twice. I tried it, this version takes 10 seconds on leetcode, my version above is only push(root) once, and it takes 8 seconds.