Leetcode每日一题-20240921
原题链接:对称二叉树
这个是个比较简单的题,可以用广度优先搜索比较对称的那个树是否相同。
递归方式的实现简单易懂,但耗时会高一些。
class Solution:
def isSymmetric(self, root: Optional[TreeNode]) -> bool:
def cmp(r1, r2):
if (r1 is None) and (r2 is None):
return True
elif (r1 is not None) and (r2 is not None):
if r1.val != r2.val:
return False
else:
return cmp(r1.left, r2.right) and cmp(r1.right, r2.left)
else:
return False
return cmp(root.left, root.right)
迭代方式实现广度优先搜索:
class Solution:
def isSymmetric(self, root: Optional[TreeNode]) -> bool:
if (root.left is None) and (root.right is None):
return True
elif (root.left is not None) and (root.right is not None):
q = [root.left, root.right]
while q:
L, R = q.pop(0), q.pop(0)
if (L is not None) and (R is not None):
if L.val != R.val:
return False
q.extend([L.left, R.right, L.right, R.left])
elif (L is None) and (R is None):
...
else:
return False
return True
else:
return False
上面是能做出来,但细节上不够好,代码的写法不够“优雅”,root
根节点应该先判断是否为空,而不是上来就先判断左右子节点是否为空。
上面是第一时间脑袋里有想法写出来的结果,就不改了,潜意识里的代码写法还是不够好。
评论区