给定一个二叉树,检查它是否是镜像对称的。
例如,二叉树 [1,2,2,3,4,4,3] 是对称的。
但是下面这个 [1,2,2,null,3,null,3] 则不是镜像对称的:
进阶:
你可以运用递归和迭代两种方法解决这个问题吗?
来源:力扣(LeetCode)
链接:https://leetcode-cn.com/problems/symmetric-tree
python
# 0101.对称二叉树
class Solution:
def isSymmetric(self, root: TreeNode) -> bool:
if not root:
return True
return self.compare(root.left, root.right)
# 递归法
def compare(self, left, right):
# 1.处理空节点的情况
if left == None and right != None:
return False
elif left != None and right == None:
return False
elif left == None and right == None:
return True
# 2.处理数值不等的情况
elif left.val != right.val:
return False
# 3.左右节点非空且数值相同,递归做下一层的判断
# 外侧节点是否相等
outside = self.compare(left.left, right.right)
# 内侧节点是否相等
inside = self.compare(left.right, right.left)
# 左子树中,右子树中,逻辑处理
isSame = outside and inside
return isSame
# 迭代法-使用队列
class Solution1:
def isSymmetric(self, root: TreeNode) -> bool:
if not root:
return True
from collections import deque
queue = deque()
queue.append(root.left)
queue.append(root.right)
# 两树是否相互翻转
while queue:
leftNode = queue.popleft()
rightNode = queue.popleft()
# 两节点空,对称
if not leftNode and not rightNode:
continue
# 左右节点有空节点或者节点值不等时,直接返回Fasle
if not leftNode or not rightNode or leftNode.val != rightNode.val:
return False
# 处理对称下的遍历翻转
# 左子树左孩子-右子树的右孩子 && 左子树右孩子-右子树的左孩子
queue.append(leftNode.left)
queue.append(rightNode.right)
queue.append(leftNode.right)
queue.append(rightNode.left)
return True
golang
package binaryTree
// 递归
func defs(left, right *TreeNode) bool {
// 两节点空->true && 有空节点->false && 值不等的-> false
if left == nil && right == nil {
return true
}
if left == nil || right == nil {
return false
}
if left.Val != right.Val {
return false
}
// 左子树左节点-右子树右节点 && 左子树右节点&右子树左节点
return defs(left.Left, right.Right) && defs(left.Right, right.Left)
}
func isSymmetric(root *TreeNode) bool {
return defs(root.Left, root.Right)
}
// 迭代
func isSymmetric2(root *TreeNode) bool {
var queue []*TreeNode
if root != nil {
queue = append(queue, root.Left, root.Right)
}
for len(queue) > 0 {
left := queue[0]
right := queue[1]
queue = queue[2:]
if left == nil && right == nil {
continue
}
if left == nil || right == nil || left.Val != right.Val {
return false
}
queue = append(queue, left.Left, right.Right, right.Left, left.Right)
}
return true
}