题目描述
给定一个二叉树,检查它是否是镜像对称的。
递归
# Definition for a binary tree node.
# class TreeNode:
# def __init__(self, x):
# self.val = x
# self.left = None
# self.right = None
class Solution:
def isSymmetric(self, root: TreeNode) -> bool:
def hanshu(root1,root2):
if type(root1)!=type(root2):
return False
elif not(root1 or root2):
return True
else:
return root1.val==root2.val and hanshu(root1.left,root2.right) and hanshu(root1.right,root2.left)
if not root:
return True
return hanshu(root.left,root.right)
把从头结点开始之后,左节点和右节点对称比较
执行用时 :64 ms, 在所有 Python3 提交中击败了8.10%的用户
内存消耗 :13.5 MB, 在所有 Python3 提交中击败了5.17%的用户
迭代
# Definition for a binary tree node.
# class TreeNode:
# def __init__(self, x):
# self.val = x
# self.left = None
# self.right = None
class Solution:
def isSymmetric(self, root: TreeNode) -> bool:
if not root:
return True
from collections import deque
d=deque([root.left,root.right])
while d:
right=d.pop()
left=d.pop()
if type(right)!=type(left): #有一个是空
return False
elif not (left and right): #两个都是空
continue #跳过当前这个循环,进行下一次比较
else: #两个都有值
if right.val != left.val:
return False
else: #两个值相等,把下一组数据放到d里面去
d.extend([left.right,right.left,left.left,right.right])
return True
看题解里面有用deque的就用了,不过感觉直接用数组也可以
执行用时 :40 ms, 在所有 Python3 提交中击败了62.27%的用户
内存消耗 :13.6 MB, 在所有 Python3 提交中击败了5.17%的用户