二叉树比较【难度:2级】:
答案1:
def compare(a, b):
return a.val == b.val and compare(a.left, b.left) and compare(a.right, b.right) if a and b else a == b
答案2:
def compare(a, b):
if a is None or b is None:
return a is b
return a.val == b.val and compare(a.left, b.left) and compare(a.right, b.right)
答案3:
compare = lambda a, b: (
a and b
and
a.val == b.val
and compare(a.left , b.left )
and compare(a.right, b.right)
or
a == b
)
答案4:
def compare(a, b):
l1, l2 = [],[]
in_order(a,l1)
in_order(b,l2)
return (l1 == l2)
def in_order(node, list):
if node == None:
return
if node.left != None:
in_order(node.left, list)
list.append(node.val)
if node.right != None:
in_order(node.right,list)
答案5:
def compare(a, b):
return a and b and a.val == b.val and compare(a.left, b.left) and compare(a.right, b.right) \
or a is b is None
答案6:
def compare(a, b):
if a is None and b is None:
return True
if a is not None and b is not None:
if a.val != b.val:
return False
else:
return compare(a.left, b.left) and compare(a.right, b.right)
return False
答案7:
def compare(a, b):
if (a == None and b == None):
return True
if ((a == None) ^ (b == None)) or (a.val != b.val):
return False
return (compare(a.left, b.left) and compare(a.right, b.right))
答案8:
def compare(a, b):
return True if a == b == None else False if (a == None and b != None) or (a != None and b == None) else compare(a.left, b.left) and compare(a.right, b.right) if a.val == b.val else False
答案9:
from operator import eq
def tree_to_inorder_list(node):
return tree_to_inorder_list(node.left) + [node.val] + tree_to_inorder_list(node.right) if node else []
def compare(a, b):
return eq(*map(tree_to_inorder_list, (a, b)))
答案10:
def compare(a, b):
if not a and not b:
return True
if a and not b:
return False
if not a and b:
return False
return a.val == b.val and compare(a.left, b.left) and compare(a.right, b.right)