MCPcopy Create free account
hub / github.com/TheAlgorithms/Python / BinaryTree

Class BinaryTree

data_structures/binary_tree/basic_binary_tree.py:32–104  ·  view source on GitHub ↗

Source from the content-addressed store, hash-verified

30
31@dataclass
32class BinaryTree:
33 root: Node
34
35 def __iter__(self) -> Iterator[int]:
36 return iter(self.root)
37
38 def __len__(self) -> int:
39 return len(self.root)
40
41 @classmethod
42 def small_tree(cls) -> BinaryTree:
43 """
44 Return a small binary tree with 3 nodes.
45 >>> binary_tree = BinaryTree.small_tree()
46 >>> len(binary_tree)
47 3
48 >>> list(binary_tree)
49 [1, 2, 3]
50 """
51 binary_tree = BinaryTree(Node(2))
52 binary_tree.root.left = Node(1)
53 binary_tree.root.right = Node(3)
54 return binary_tree
55
56 @classmethod
57 def medium_tree(cls) -> BinaryTree:
58 """
59 Return a medium binary tree with 3 nodes.
60 >>> binary_tree = BinaryTree.medium_tree()
61 >>> len(binary_tree)
62 7
63 >>> list(binary_tree)
64 [1, 2, 3, 4, 5, 6, 7]
65 """
66 binary_tree = BinaryTree(Node(4))
67 binary_tree.root.left = two = Node(2)
68 two.left = Node(1)
69 two.right = Node(3)
70 binary_tree.root.right = five = Node(5)
71 five.right = six = Node(6)
72 six.right = Node(7)
73 return binary_tree
74
75 def depth(self) -> int:
76 """
77 Returns the depth of the tree
78
79 >>> BinaryTree(Node(1)).depth()
80 1
81 >>> BinaryTree.small_tree().depth()
82 2
83 >>> BinaryTree.medium_tree().depth()
84 4
85 """
86 return self._depth(self.root)
87
88 def _depth(self, node: Node | None) -> int:
89 if not node:

Callers 2

small_treeMethod · 0.70
medium_treeMethod · 0.70

Calls

no outgoing calls

Tested by

no test coverage detected