Tree Level Sum
Given the root node of a binary tree, implement a function that returns the sum of all nodes' values at a specified level.
[ 1, null, 2, 3 ]
Explanation. The tree is as follows: 1 \ 2 / 3 Level 2 has one node with value 3.
[ 3, 9, 20, null, null, 15, 7 ]
Explanation. The tree is as follows: 3 / \ 9 20 / \ 15 7 Level 2 has two nodes, with values 15 and 7, and their sum is 22.
[ 1 ]
Explanation. The tree has only one node at level 1 with the value 1.
Follow-up: How would your function change if the tree was a binary search tree and you were asked to return the sum of all values between two given levels?
The tree will have at least one node and the given level will always be valid and less than the height of the tree.
- Views
- 2