|
| 1 | +""" |
| 2 | +Sum of all nodes in a binary tree. |
| 3 | +
|
| 4 | +Python implementation: |
| 5 | + O(n) time complexity - Recurses through :meth:`depth_first_search` |
| 6 | + with each element. |
| 7 | + O(n) space complexity - At any point in time maximum number of stack |
| 8 | + frames that could be in memory is `n` |
| 9 | +""" |
| 10 | + |
| 11 | + |
| 12 | +from __future__ import annotations |
| 13 | + |
| 14 | +from collections.abc import Iterator |
| 15 | + |
| 16 | + |
| 17 | +class Node: |
| 18 | + """ |
| 19 | + A Node has a value variable and pointers to Nodes to its left and right. |
| 20 | + """ |
| 21 | + |
| 22 | + def __init__(self, value: int) -> None: |
| 23 | + self.value = value |
| 24 | + self.left: Node | None = None |
| 25 | + self.right: Node | None = None |
| 26 | + |
| 27 | + |
| 28 | +class BinaryTreeNodeSum: |
| 29 | + r""" |
| 30 | + The below tree looks like this |
| 31 | + 10 |
| 32 | + / \ |
| 33 | + 5 -3 |
| 34 | + / / \ |
| 35 | + 12 8 0 |
| 36 | +
|
| 37 | + >>> tree = Node(10) |
| 38 | + >>> sum(BinaryTreeNodeSum(tree)) |
| 39 | + 10 |
| 40 | +
|
| 41 | + >>> tree.left = Node(5) |
| 42 | + >>> sum(BinaryTreeNodeSum(tree)) |
| 43 | + 15 |
| 44 | +
|
| 45 | + >>> tree.right = Node(-3) |
| 46 | + >>> sum(BinaryTreeNodeSum(tree)) |
| 47 | + 12 |
| 48 | +
|
| 49 | + >>> tree.left.left = Node(12) |
| 50 | + >>> sum(BinaryTreeNodeSum(tree)) |
| 51 | + 24 |
| 52 | +
|
| 53 | + >>> tree.right.left = Node(8) |
| 54 | + >>> tree.right.right = Node(0) |
| 55 | + >>> sum(BinaryTreeNodeSum(tree)) |
| 56 | + 32 |
| 57 | + """ |
| 58 | + |
| 59 | + def __init__(self, tree: Node) -> None: |
| 60 | + self.tree = tree |
| 61 | + |
| 62 | + def depth_first_search(self, node: Node | None) -> int: |
| 63 | + if node is None: |
| 64 | + return 0 |
| 65 | + return node.value + ( |
| 66 | + self.depth_first_search(node.left) + self.depth_first_search(node.right) |
| 67 | + ) |
| 68 | + |
| 69 | + def __iter__(self) -> Iterator[int]: |
| 70 | + yield self.depth_first_search(self.tree) |
| 71 | + |
| 72 | + |
| 73 | +if __name__ == "__main__": |
| 74 | + import doctest |
| 75 | + |
| 76 | + doctest.testmod() |
0 commit comments