对称的二叉树
问题
请实现一个函数,用来判断一棵二叉树是不是对称的。如果一棵二叉树和它的镜像一样,那么它是对称的。
例如,二叉树 [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
示例 1:
输入:root = [1,2,2,3,4,4,3]
输出:true
示例 2:
输入:root = [1,2,2,null,3,null,3]
输出:false
链接:https://leetcode-cn.com/problems/dui-cheng-de-er-cha-shu-lcof
解答
class Solution:
def isSymmetric(self, root: TreeNode) -> bool:
def recur(L, R):
if not L and not R: return True
if not L or not R or L.val != R.val: return False
return recur(L.left, R.right) and recur(L.right, R.left)
return recur(root.left, root.right) if root else True
有的东西,只有自己写一遍,脑子过一遍,才能知道自己是否真的明白了,才能说自己了解了。
二刷时
# Definition for a binary tree node.
# class TreeNode:
# def __init__(self, x):
# self.val = x
# self.left = None
# self.right = None
from collections import deque
class Solution:
def isSymmetric(self, root: TreeNode) -> bool:
res = []
if not root:
return True
que = deque()
que.append(root)
while que:
temp = []
for _ in range(len(que)):
node = que.popleft()
if node == 'null':
temp.append('null')
continue
temp.append(node.val)
if node.left:
que.append(node.left)
elif not node.left:
que.append('null')
if node.right:
que.append(node.right)
elif not node.right:
que.append('null')
res.append(temp)
for i in res[1:]:
# len(i)->奇数
if len(i)%2 != 0:
return False
# len(i)->偶数
ping = int(len(i)/2)
if i[:ping] == i[ping:][::-1]:
continue
else:
return False
return True