Sum of Roots in Binary Search Tree
easySave
Binary Search TreeDepth-First SearchTree
Given a Binary Search Tree (BST), calculate the sum of the values of all the root nodes from the individual subtrees. A root node of a subtree is defined as the node that does not have a parent node within its subtree.
Example 1
Input
[ [ 10, 5, 15, 3, 7, null, 18 ] ]
Output
10
Explanation. This tree contains only one subtree which is the tree itself. The root node is 10.
Example 2
Input
[ [ 10, 5, 15, 3, 7, 13, 18, 1, 6 ] ]
Output
28
Explanation. The tree has following roots of subtrees - 10, 15, 5, 3. Sum = 10 + 15 + 5 + 3 = 33.
Follow-up: Can you optimize your solution to handle large trees efficiently?
Constraints:
The given binary tree will have at least one node.
- Views
- 3