sum of all nodes in a binary tree python implementation on time complexity recurses through meth depthfirstsearch with each element on space complexity at any point in time maximum number of stack frames that could be in memory is n a node has a value variable and pointers to nodes to its left and right def initself tree node none self tree tree def depthfirstsearchself node node none int if node is none return 0 return node value self depthfirstsearchnode left self depthfirstsearchnode right def iterself iteratorint yield self depthfirstsearchself tree if name main import doctest doctest testmod a node has a value variable and pointers to nodes to its left and right 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
from __future__ import annotations

from collections.abc import Iterator


class Node:
    

    def __init__(self, value: int) -> None:
        self.value = value
        self.left: Node | None = None
        self.right: Node | None = None


class BinaryTreeNodeSum:
    r

    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()