给定一个二叉树,检查它是否是镜像对称的。
例如,二叉树 [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
如果你可以运用递归和迭代两种方法解决这个问题,会很加分。
- 均为None ,
- symmetric 左孩子,右孩子都不存在,并且值相等,
- symmetric 右子树 和 另一棵树的左子树相等,
- 左子树和另一颗树的右子树相等
迭代写法,有点像非递归层次遍历的处理过程
这里要注意,Java 的queue的poll 函数的返回值,当队列为空时,poll() 不会奔溃,只会返回 null 而Python3 中的队列会抛出异常
学会Python 的三目表达式的写法
时间复杂度: O(N)- 空间复杂度: O(1)
Java 版本
class Solution {
public boolean isSymmetric(TreeNode root) {
Queue<TreeNode> q = new LinkedList<>();
q.add(root);
q.add(root);
while(!q.isEmpty()){
TreeNode n1= q.poll();
TreeNode n2= q.poll();
if(n1 == null && n2 == null){
continue;
}
if(n1 == null || n2 == null){
return false;
}
if(n1.val!=n2.val){
return false;
}
q.add(n1.left);
q.add(n2.right);
q.add(n1.right);
q.add(n2.left);
}
return true;
}
}
class Solution:
def isSymmetric(self, root: TreeNode) -> bool:
lst=[]
lst.append(root)
lst.append(root)
while lst:
t1 = lst.pop() if lst else None
t2 = lst.pop() if lst else None
if not t1 and not t2: continue
if not t1 or not t2:
return False
if t1.val != t2.val:
return False
lst.append(t1.left)
lst.append(t2.right)
lst.append(t1.right)
lst.append(t2.left)
return True
递归写法, 需要小心的判断边界条件
(r1 == null && r2 == null)
(r1 == null || r2 == null)
常见的判断两颗树相等的条件
时间复杂度: O(N)- 空间复杂度: O(n)
Java 版本
class Solution {
public boolean isSymmetric(TreeNode root) {
if(root == null){
return true;
}
return isMirror(root.left,root.right);
}
public boolean isMirror(TreeNode r1,TreeNode r2){
if(r1 == null && r2 == null){
return true;
}
if(r1 == null || r2 == null){
return false;
}
return (r1.val == r2.val)&&isMirror(r1.left,r2.right)&&isMirror(r1.right,r2.left);
}
}
Python3 版本
class Solution:
def isSymmetric(self, root: TreeNode) -> bool:
if root is None:
return True
return self.isMirror(root.left , root.right)
def isMirror(self,n1,n2):
if not n1 and not n2:
return True
if not n1 or not n2:
return False
return (n1.val == n2.val) and self.isMirror(n1.left , n2.right) and self.isMirror(n1.right , n2.left)
还有一种方法,将一棵树的其中一边转过来,和另一边比较,反正是对称的,必然相等,否则不等。
Python3 实现
class Solution:
def isSymmetric(self, root: TreeNode) -> bool:
# Revert TreeNode
def revert(node):
if not node: return
node.left, node.right = node.right, node.left
revert(node.left)
revert(node.right)
def isEqual(left, right):
if not left and not right: return True
if not left or not right: return False
if left.val != right.val:
return False
return isEqual(left.left, right.left) and isEqual(left.right, right.right)
if not root:
return True
revert(root.right)
return isEqual(root.left, root.right)