1. 对称的二叉树
请实现一个函数,用来判断一棵二叉树是不是对称的。
方法一:
class TreeNode:
def __init__(self, val=0, left=None, right=None):
self.val = val
self.left = left
self.right = right
def isSymmetric(root):
if not root:
return True
def recur(left_node, right_node):
if not left_node and not right_node:
return True
if not left_node or not right_node or left_node.val!= right_node.val:
return False
return recur(left_node.left, right_node.right) and recur(left_node.right, right_node.left)
return recur(root.left, root.right)
方法二:
class TreeNode:
def __init__(self, val=0, left=None, right=None):
self.val = val
self.left = left
self.right = right
def isSymmetric(root):
if not root:
return True
queue = [(root.left, root.right)]
while queue:
left_node, right_node = queue.pop(0)
if not left_node and not right_node:
continue
if not left_node or not right_node or left_node.val!= right_node.val:
return False
queue.append((left_node.left, right_node.right))
queue.append((left_node.right, right_node.left))
return True
方法三:
class TreeNode:
def __init__(self, val=0, left=None, right=None):
self.val = val
self.left = left
self.right = right
def isSymmetric(root):
def isMirror(left_tree, right_tree):
if not left_tree and not right_tree:
return True
if not left_tree or not right_tree:
return False
return left_tree.val == right_tree.val and isMirror(left_tree.left, right_tree.right) and isMirror(left_tree.right, right_tree.left)
return isMirror(root, root)
方法四:
class TreeNode:
def __init__(self, val=0, left=None, right=None):
self.val = val
self.left = left
self.right = right
def isSymmetric(root):
if not root:
return True
def inorder_traversal(node, values):
if not node:
values.append(None)
return
inorder_traversal(node.left, values)
values.append(node.val)
inorder_traversal(node.right, values)
def reverse_inorder_traversal(node, values):
if not node:
values.append(None)
return
reverse_inorder_traversal(node.right, values)
values.append(node.val)
reverse_inorder_traversal(node.left, values)
normal_order = []
reverse_order = []
inorder_traversal(root, normal_order)
reverse_inorder_traversal(root, reverse_order)
return normal_order == reverse_order
方法五:
class TreeNode:
def __init__(self, val=0, left=None, right=None):
self.val = val
self.left = left
self.right = right
def isSymmetric(root):
if not root:
return True
stack = [(root.left, root.right)]
while stack:
left_node, right_node = stack.pop()
if not left_node and not right_node:
continue
if not left_node or not right_node or left_node.val!= right_node.val:
return False
stack.append((left_node.left, right_node.right))
stack.append((left_node.right, right_node.left))
return True