描述
Given a binary tree, check whether it is a mirror of itself (ie, symmetric around its center)
给定一个二叉树,检查它是否是镜像对称的
例子
思路
第100题:两个树是否相同
- 比较具有相同的值
- 比较结点的左子树和另一个结点的左子树
此题:两个树互为镜像
. 结点具有相同的值
. 比较结点的左子树和另一个节点的右子树
答案
- 递归
python
class Solution:
def isSymmetric(self, root: TreeNode) -> bool:
'''
如此,虽然写着方便,但会多一倍的重复计算 要算 self.check(root.left, root.right) 和self.check(root.right, root.left)
return self.check(root, root)
'''
if root: #不为空
return self.check(root.left,root.right)
return True #为空
def check(self,p,q):
if not p and not q:
return True
if not p or not q or p.val != q.val:
return False
return self.check(p.left, q.right) and self.check(p.right, q.left)
java
class Solution {
public boolean isSymmetric(TreeNode root) {
/*
如此,虽然写着方便,但会多一倍的重复计算 要算 check(root.left, root.right) 和check(root.right, root.left)
return check(root, root)
*/
if (root != null)
return check(root.left, root.right);
return true; //为空
}
public boolean check(TreeNode p, TreeNode q)
{
if (p == null && q == null)
return true;
if (p == null || q == null || p.val != q.val)
return false;
return check(p.left, q.right) && check(p.right, q.left);
}
}
- 迭代,使用栈
python
class Solution:
def isSymmetric(self, root: TreeNode) -> bool:
if not root:
return True
arr=[]
arr.extend([root.left, root.right])
while len(arr)>0:
p = arr.pop()
q = arr.pop()
if not q and not p: #如果该两个结点为null,不用比较,直接再取两个
continue
if (not q or not p): #有一个时Null
return False
# 都不是null
if p.val != q.val:
return False
arr.extend([p.left, q.right, p.right,q.left])
return True
java
class Solution {
public boolean isSymmetric(TreeNode root) {
if (root == null)
return true;
Stack<TreeNode> s = new Stack<TreeNode>();
s.push(root.left);
s.push(root.right);
while (s.size()>0)
{
TreeNode p = s.pop();
TreeNode q = s.pop();
if (p==null && q==null) //两个都是NOne
continue;
if (p==null || q==null) //有一个为None
return false;
//两个都不是None
if (p.val != q.val)
return false;
s.push(p.left);
s.push(q.right);
s.push(p.right);
s.push(q.left);
}
return true;
}
}