https://leetcode.com/problems/symmetric-tree/
Given a binary tree, check whether it is a mirror of itself (ie, symmetric around its center).
For example, this binary tree [1,2,2,3,4,4,3]
is symmetric:
1 / \ 2 2 / \ / \ 3 4 4 3
But the following [1,2,2,null,3,null,3]
is not:
1 / \ 2 2 \ \ 3 3
/**
* 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 isSymmetric(TreeNode* root) {
return helper(root,root);
}
bool helper(TreeNode* root1,TreeNode* root2){
if(root1==NULL && root2==NULL){
return true;
}
if(root1==NULL || root2==NULL){
return false;
}
if(root1->val!=root2->val){
return false;
}
return helper(root1->left,root2->right) & helper(root1->right,root2->left);
}
};
非递归解法,用两个队列分别保存左子树节点和右子树节点,每次从两个队列中分别取出元素,如果两个元素的值相等,则继续把他们的左右节点加入左右队列。要注意每次取出的两个元素,左队列元素的左孩子要和右队列元素的右孩子要同时不为空或者同时为空,否则不可能对称,同理左队列元素的右孩子要和右队列元素的左孩子也一样。
class Solution {
public:
bool isSymmetric(TreeNode* root) {
if(root==NULL){
return true;
}
queue<TreeNode*> qleft;
queue<TreeNode*> qright;
if(root->left)
qleft.push(root->left);
if(root->right)
qright.push(root->right);
while(!qleft.empty() && !qright.empty()){
TreeNode* left=qleft.front();qleft.pop();
TreeNode* right=qright.front();qright.pop();
if(left->val==right->val){
if(left->left&&right->right){
qleft.push(left->left);
qright.push(right->right);
}else if(left->left || right->right){
return false;
}
if(left->right&&right->left){
qleft.push(right->left);//
qright.push(left->right);
}else if(left->right || right->left){
return false;
}
}else{
return false;
}
}
return qleft.empty()&&qright.empty();
}
};