data_structures.binary_tree.binary_tree_node_sum

Sum of all nodes in a binary tree.

Python implementation:
O(n) time complexity - Recurses through 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

Classes

BinaryTreeNodeSum

The below tree looks like this

Node

A Node has a value variable and pointers to Nodes to its left and right.

Module Contents

class data_structures.binary_tree.binary_tree_node_sum.BinaryTreeNodeSum(tree: Node)
The below 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
__iter__() collections.abc.Iterator[int]
tree
class data_structures.binary_tree.binary_tree_node_sum.Node(value: int)

A Node has a value variable and pointers to Nodes to its left and right.

left: Node | None = None
right: Node | None = None
value