[leetCode]101对称二叉树
解法1
使用递归求解,把该问题转化为:两棵树在什么情况下是镜像的?
- 两颗树的根节点相同
- 每个树的右子树和令一棵树的左子树相同
这样可以通过两个指针的同时移动来遍历这棵树,一开始指针p、q同时指向根节点。指针p左移时,q右移动判断值是否相等; 指针p右移时,q左移动判断值是否相等。
C++
/**
* 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 && !q) return true;//两颗树都为空
if(!p || !q) return false;//一棵树为空,一棵树不为空
//p指针往左移动时,q指针往右移动;p指针往右移动时,q指针往左移动;
return p->val == q->val && check(p->left,q->right) && check(p->right,q->left);
}
bool isSymmetric(TreeNode* root) {
return check(root, root);
}
};
java
/**
* Definition for a binary tree node.
* public class TreeNode {
* int val;
* TreeNode left;
* TreeNode right;
* TreeNode(int x) { val = x; }
* }
*/
class Solution {
public boolean check(TreeNode p, TreeNode q){
if(p == null && q == null)return true;
if(p == null || q == null)return false;
return p.val == q.val && check(p.left,q.right) && check(p.right,q.left);
}
public boolean isSymmetric(TreeNode root) {
return(check(root,root));
}
}
解法二
迭代解法。首先创建一个队列,先将根节点添加两次,判断是否对称,再将两棵树的子节点按左右相反顺序插入队列,如果是对称的则每次取出的两个节点的值是相等的。当队列为空或者不满足对称时停止。
C++
class Solution {
public:
bool check(TreeNode *u, TreeNode *v) {
queue <TreeNode*> q;
q.push(u); q.push(v);
while (!q.empty()) {
u = q.front(); q.pop();
v = q.front(); q.pop();
if (!u && !v) continue;
if ((!u || !v) || (u->val != v->val)) return false;
q.push(u->left);
q.push(v->right);
q.push(u->right);
q.push(v->left);
}
return true;
}
bool isSymmetric(TreeNode* root) {
return check(root, root);
}
};
java
class Solution {
public boolean check(TreeNode u, TreeNode v){
Queue<TreeNode> q = new LinkedList<TreeNode>();
q.offer(u);//插入两个根节点
q.offer(v);
while(!q.isEmpty()){
u = q.poll();
v = q.poll();
if(u == null && v == null ) continue;
if( (u == null || v ==null) || (u.val != v.val) ) return false;
q.offer(u.left);
q.offer(v.right);
q.offer(u.right);
q.offer(v.left);
}
return true;
}
public boolean isSymmetric(TreeNode root) {
return(check(root,root));
}
}
参考
作者:LeetCode-Solution
链接:https://leetcode-cn.com/problems/symmetric-tree/solution/dui-cheng-er-cha-shu-by-leetcode-solution/
来源:力扣(LeetCode)
著作权归作者所有。商业转载请联系作者获得授权,非商业转载请注明出处。