给定一个二叉树,检查它是否是镜像对称的。
例如,二叉树 [1,2,2,3,4,4,3] 是对称的。
1
/ \
2 2
/ \ / \
3 4 4 3
但是下面这个 [1,2,2,null,3,null,3] 则不是镜像对称的:
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) {
if(!root) return true;
return istrue(root->left,root->right);
}
private:
bool istrue(TreeNode *a, TreeNode *b){
if(!a&&!b) return true;
if(!a||!b) return false;
if(a->val!=b->val) return false;
return istrue(a->left,b->right)&&istrue(a->right,b->left);
}
};
迭代方法:队列
队列中先加入两次根节点;
每次出队两个点,判断是否相同;
再把出队的两个点的左右反向交替入队;
/**
* 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) {
Q.push(root);
Q.push(root);
while(!Q.empty()){
TreeNode *a=Q.front();
Q.pop();
TreeNode *b=Q.front();
Q.pop();
if(!a&&!b) continue;
if(!a||!b) return false;
if(a->val!=b->val) return false;
Q.push(a->left);
Q.push(b->right);
Q.push(a->right);
Q.push(b->left);
}
return true;
}
private:
queue<TreeNode*> Q;
};

本文探讨了如何检查一个二叉树是否为镜像对称。提供了递归和迭代两种方法实现,递归方法通过比较左右子树来判断,而迭代方法使用队列进行节点的配对比较。
771

被折叠的 条评论
为什么被折叠?



