leetcood学习笔记-101-对称二叉树
题目描述:

方法一:递归:
class Solution: def isSymmetric(self, root: TreeNode) -> bool: if not root: return True def Tree(p, q): if not p and not q: return True if p and q and p.val == q.val : return Tree(p.left, q.right) and Tree(p.right, q.left) return False return Tree(root.left, root.right
方法二:迭代:
class Solution:
def isSymmetric(self, root: TreeNode) -> bool:
if not root: return True
def Tree(p, q):
stack = [(q, p)]
while stack:
a, b = stack.pop()
if not a and not b:
continue
if a and b and a.val == b.val:
stack.append((a.left, b.right))
stack.append((a.right,b.left))
else:
return False
return True
return Tree(root.left, root.right)
def isSymmetric(self, root: TreeNode) -> bool:
if not root: return True
def Tree(p, q):
stack = [(q, p)]
while stack:
a, b = stack.pop()
if not a and not b:
continue
if a and b and a.val == b.val:
stack.append((a.left, b.right))
stack.append((a.right,b.left))
else:
return False
return True
return Tree(root.left, root.right)
方法三:层次遍历
# 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 ans = [root.left,root.right] while ans: tmp,n= [],len(ans) for i in range(n): r = ans.pop(0) if r: ans.append(r.left) ans.append(r.right) tmp.append(r.val) else: tmp.append(None) if tmp != tmp[::-1]: return False return True
浙公网安备 33010602011771号