都是写过的两个题,虽然写出来了,但是一碰到递归下手还是不自信;迭代法也还需要更加熟练
101.对称二叉树
# 递归法
class Solution:
def isSymmetric(self, root: Optional[TreeNode]) -> bool:
def compare(node1,node2):
if not node1 and not node2:
return True
if not node1 and node2 or not node2 and node1 or node1.val!=node2.val:
return False
return compare(node1.left,node2.right) and compare(node1.right,node2.left)
return compare(root.left,root.right)
# 迭代法
class Solution:
def isSymmetric(self, root: Optional[TreeNode]) -> bool:
queue = [root.left,root.right]
while(queue):
node1 = queue.pop(0)
node2 = queue.pop(0)
if node1 and node2 and node1.val==node2.val:
queue.append(node1.left)
queue.append(node2.right)
queue.append(node1.right)
queue.append(node2.left)
elif not node1 and not node2:
continue
elif not node1 and node2 or not node2 and node1 or node1.val!=node2.val:
return False
return True
# 递归法
class Solution:
def invertTree(self, root: Optional[TreeNode]) -> Optional[TreeNode]:
if not root:
return
root.left,root.right = root.right,root.left
self.invertTree(root.left)
self.invertTree(root.right)
return root
# 迭代法
class Solution:
def invertTree(self, root: Optional[TreeNode]) -> Optional[TreeNode]:
stack = [root]
while(stack):
node = stack.pop()
if node:
node.left,node.right = node.right,node.left
stack.append(node.right)
stack.append(node.left)
return root