| 70 | |
| 71 | @dataclass |
| 72 | class BinaryTree: |
| 73 | root: Node |
| 74 | |
| 75 | def __iter__(self) -> Iterator[int]: |
| 76 | """ |
| 77 | >>> list(BinaryTree.build_a_tree()) |
| 78 | [1, 2, 7, 11, 15, 29, 35, 40] |
| 79 | """ |
| 80 | return iter(self.root) |
| 81 | |
| 82 | def __len__(self) -> int: |
| 83 | """ |
| 84 | >>> len(BinaryTree.build_a_tree()) |
| 85 | 8 |
| 86 | """ |
| 87 | return len(self.root) |
| 88 | |
| 89 | def __str__(self) -> str: |
| 90 | """ |
| 91 | Returns a string representation of the inorder traversal of the binary tree. |
| 92 | |
| 93 | >>> str(list(BinaryTree.build_a_tree())) |
| 94 | '[1, 2, 7, 11, 15, 29, 35, 40]' |
| 95 | """ |
| 96 | return str(list(self)) |
| 97 | |
| 98 | @property |
| 99 | def is_sum_tree(self) -> bool: |
| 100 | """ |
| 101 | >>> BinaryTree.build_a_tree().is_sum_tree |
| 102 | False |
| 103 | >>> BinaryTree.build_a_sum_tree().is_sum_tree |
| 104 | True |
| 105 | """ |
| 106 | return self.root.is_sum_node |
| 107 | |
| 108 | @classmethod |
| 109 | def build_a_tree(cls) -> BinaryTree: |
| 110 | r""" |
| 111 | Create a binary tree with the specified structure: |
| 112 | 11 |
| 113 | / \ |
| 114 | 2 29 |
| 115 | / \ / \ |
| 116 | 1 7 15 40 |
| 117 | \ |
| 118 | 35 |
| 119 | >>> list(BinaryTree.build_a_tree()) |
| 120 | [1, 2, 7, 11, 15, 29, 35, 40] |
| 121 | """ |
| 122 | tree = BinaryTree(Node(11)) |
| 123 | root = tree.root |
| 124 | root.left = Node(2) |
| 125 | root.right = Node(29) |
| 126 | root.left.left = Node(1) |
| 127 | root.left.right = Node(7) |
| 128 | root.right.left = Node(15) |
| 129 | root.right.right = Node(40) |
no outgoing calls
no test coverage detected