实施并测试以下BST方法
我正在使用此代码实现二叉树节点类和二叉树类来检查两个BST是否相同。该方法是递归的,需要辅助功能。
这是我到目前为止所做的,我在编写主程序时遇到了麻烦。有人可以帮帮我吗。
def is_identical(self, rs):
identical = self._is_identical_aux(self._root, rs._root)
return identical
def _is_identical_aux(self, node1, node2):
result = True
if node1._value != node2._value:
result = False
if node1._left is not None and node2._left is not None and result == True:
result = self._is_identical_aux(node1._left, node2._left)
if node1.right is not None and node2._right is not None and result == True:
result = self._is_identical_aux(node1._right, node2._right)
return result
答案 0 :(得分:0)
您的代码看起来不对。请尝试以下代码。
def _is_identical_aux(self, node1, node2):
if node1 is None and node2 is None:
return True
if node1 is not None and node2 is not None:
return ((node1._value == node2._value) and
_is_identical_aux(node1.left, node2.left) and
_is_identical_aux(node1.right, node2.right))
return False
以下是测试:
class Node:
def __init__(self, data):
self._value = data
self.left = None
self.right = None
def _is_identical_aux(node1, node2):
if node1 is None and node2 is None:
return True
if node1 is not None and node2 is not None:
return ((node1._value == node2._value) and
_is_identical_aux(node1.left, node2.left) and
_is_identical_aux(node1.right, node2.right))
return False
root1 = Node(7)
root1.left = Node(3)
root1.right = Node(2)
root1.left.left = Node(123)
root1.left.right = Node(231)
root1.right.left = Node(9)
root1.right.right = Node(5)
root2 = Node(7)
root2.left = Node(3)
root2.right = Node(2)
root2.left.left = Node(123)
root2.left.right = Node(231)
root2.right.left = Node(9)
root2.right.right = Node(5)
root3 = Node(7)
root3.left = Node(3)
root3.right = Node(2)
if _is_identical_aux(root1, root2):
print "Both trees are identical"
else:
print "Trees are not identical"
if _is_identical_aux(root1, root3):
print "Both trees are identical"
else:
print "Trees are not identical"
结果:
Both trees are identical
Trees are not identical