Problem statement

https://binarysearch.com/problems/Tree-Sum/

Solution

Just use recursive dfs.

Complexity

It is O(n) for time and O(h) for space.

Code

class Solution:
    def solve(self, root):
        if not root: return 0
        return self.solve(root.left) + self.solve(root.right) + root.val