Created
December 3, 2022 15:55
-
-
Save CaedenPH/5756aa875cbf59ddf1db9da0abbece2a to your computer and use it in GitHub Desktop.
Using recursion to get the nodes of a binary tree
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
""" | |
Generates an `Iterator` object in order to perform the `max` | |
python builtin on the tree. | |
O(n) time complexity - Recurses through :meth:`depth_first_search` | |
with each element. | |
O(n) space complexity - At any point in time maximum number of stack | |
frames that could be in memory is `n` | |
""" | |
from __future__ import annotations | |
from collections.abc import Iterator | |
class Node: | |
""" | |
A Node has a value variable and pointers to Nodes to its left and right. | |
""" | |
def __init__(self, value: int) -> None: | |
self.value = value | |
self.left: Node | None = None | |
self.right: Node | None = None | |
class BinaryTreeNodeSum: | |
r""" | |
The below finished tree looks like this | |
10 | |
/ \ | |
5 -3 | |
/ / \ | |
12 8 0 | |
>>> tree = Node(10) | |
>>> sum(BinaryTreeNodeSum(tree)) | |
10 | |
>>> tree.left = Node(5) | |
>>> sum(BinaryTreeNodeSum(tree)) | |
15 | |
>>> tree.right = Node(-3) | |
>>> sum(BinaryTreeNodeSum(tree)) | |
12 | |
>>> tree.left.left = Node(12) | |
>>> sum(BinaryTreeNodeSum(tree)) | |
24 | |
>>> tree.right.left = Node(8) | |
>>> tree.right.right = Node(0) | |
>>> sum(BinaryTreeNodeSum(tree)) | |
32 | |
""" | |
def __init__(self, tree: Node) -> None: | |
self.tree = tree | |
def depth_first_search(self, node: Node | None) -> int: | |
if node is None: | |
return 0 | |
return node.value + ( | |
self.depth_first_search(node.left) + self.depth_first_search(node.right) | |
) | |
def __iter__(self) -> Iterator[int]: | |
yield self.depth_first_search(self.tree) | |
if __name__ == "__main__": | |
import doctest | |
doctest.testmod() | |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment