Dsa
Binary Search Tree
Easy
Sum of All Nodes in BST
Given a binary search tree (BST), write a program that calculates the sum of all the nodes present in the BST.
Implement the following functions:
1. `insert(root: Optional[Node], value: int) -> Node`: Insert a value into the BST.
2. `sum_of_nodes(root: Optional[Node]) -> int`: Return the sum of all node values in the BST.
Input format:
- The first line contains an integer N (1 <= N <= 100) - the number of elements in the BST.
- The next N lines each contain one integer, the value to be inserted into the BST.
Output format:
- Output a single integer representing the sum of all nodes in the BST.
Example:
Input:
4
5
3
8
9
Output:
25
Key concepts
binary_search_treesumtraversal
Practise this out loud — free
Start a mock interview on THIS exact question — a voice AI interviewer opens with it, pushes back like a real onsite, then hands you an instant scorecard.
🎙 Practise this question now