我正在尝试测试红黑树的
rotate_left
操作。但我不断收到 RecursionError。这是我的 WIP 实现:
from dataclasses import dataclass
from enum import Enum
from typing import Optional, Generic, TypeVar
T = TypeVar('T')
class Color(Enum):
RED = 0
BLACK = 1
@dataclass
class Node(Generic[T]):
color: Color
value: T
parent: Optional['Node[T]'] = None
left: Optional['Node[T]'] = None
right: Optional['Node[T]'] = None
@dataclass
class RedBlackTree(Generic[T]):
root: Node
def rotate_left(self, x: Node[T]):
y = x.right
x.right = y.left
if y.left != None:
y.left.parent = x
y.parent = x.parent
if x.parent == None:
self.root = y
elif x == x.parent.left:
x.parent.left = y
else:
x.parent.right = y
y.left = x
x.parent = y
这是我的测试用例:
import pprint
import unittest
from src.red_black_tree import RedBlackTree, Node, Color
class TestRedBlackTreeMethods(unittest.TestCase):
def test_left_rotation(self):
node4 = Node(Color.BLACK, value=15, left=None, right=None)
node2 = Node(Color.BLACK, value=2, left=None, right=None)
node3 = Node(Color.RED, value=12, left=None, right=node4)
node1 = Node(color=Color.RED, parent=None, left=node2, right=node3, value=10)
node4.parent = node3
node3.parent = node1
node2.parent = node1
tree = RedBlackTree(root=node1)
tree.rotate_left(node1)
expected_node4 = Node(Color.BLACK, value=2, left=None, right=None)
expected_node3 = Node(color=Color.RED, left=node2, value=10)
expected_node2 = Node(Color.BLACK, value=15, left=None, right=None)
expected_node1 = Node(Color.RED, value= 12, parent=None, right=expected_node2, left=expected_node3)
expected_node2.parent = expected_node1
expected_node3.parent = expected_node1
expected_node4.parent = expected_node3
expected_tree = RedBlackTree(root=expected_node1)
self.assertEqual(tree.root.value, expected_tree.root.value)
self.assertEqual(tree.root.left.value, expected_tree.root.left.value)
self.assertEqual(tree.root.right.value, expected_tree.root.right.value)
self.assertEqual(tree.root.left.left.value, expected_tree.root.left.left.value)
self.assertEqual(tree, expected_tree)
if __name__ == '__main__':
unittest.main()
我怀疑由于
self.assertEqual(tree, expected_tree)
属性,执行 parent
会破坏堆栈。所以我想知道是否可以让unittest忽略这个属性,或者是否有更适合这种情况的方法。
我认为
assertEqual
仅限于值和核心数据类型(参见此处)。据我所知,你的树类并没有以这种时尚的方式表示。
如果检查特定节点还不够,您可能需要找到一种方法来迭代整个树。然后,您可以迭代两棵树并成对比较元素。或者,您可以使用迭代来表示树。您将比较所需的所有值写入与assertEqual 兼容的新数据类型(如列表)。然后您可以比较两个树表示。