题解 | #对称的二叉树#
对称的二叉树
https://www.nowcoder.com/practice/ff05d44dfdb04e1d83bdbdab320efbcb
python3,非递归方法,对称性,对应着回文性。
对左右子树分别做层次遍历,各自维护一个栈,因为对称性对应着回文性,所以入栈的顺序变一下,则对称性必会导致栈相同,如果不同则无对称性
class Solution:
def isSymmetrical(self , pRoot: TreeNode) -> bool:
if not pRoot:
return True
#辅助队列用于从两边层次遍历
l1 = []
l2 = []
l1.append(pRoot.left)
l2.append(pRoot.right)
while l1 and l2:
# 左右两个栈,弹出
l = l1.pop(0)
r = l2.pop(0)
if not l and not r:
continue
# 不对称的情况,直接False
if not l or not r or l.val != r.val:
return False
# 从左往右加入队列
q1.append(l.left)
q1.append(l.right)
# 从右往左加入队列
q2.append(r.right)
q2.append(r.left)
return True
查看12道真题和解析