1. Invert Binary Tree (Leetcode Number: 144)
BFS strategy is used to swap those nodes on the same level
class Solution:
def invertTree(self, root: Optional[TreeNode]) -> Optional[TreeNode]:
if root is None:
return root
root.left, root.right = root.right, root.left
# The position of following two lines could be swapped as we are using BFS strategy here
self.invertTree(root.right)
self.invertTree(root.left)
return root
2. Symmetric Tree (Leetcode Number: 101)
class Solution:
def isSymmetric(self, root: Optional[TreeNode]) -> bool:
if root is None:
return True
return self.nodecompare(root.left, root.right)
def nodecompare(self, left, right):
# The following four lines filter out all the unequal symmetric nodes
if left == None and right != None: return False
elif left != None and right == None: return False
elif left == None and right == None: return True
elif left.val != right.val: return False
outside = self.nodecompare(left.left, right.right)
inside = self.nodecompare(left.right, right.left)
ifsame = outside and inside
return ifsame