Calculating the sum of each level in the tree
Question:
Given a binary tree with nodes containing integer values. Your algorithm should calculate the sum of values in each depth and returns sums.
Example:
1
/ \
2 3
/ \ / \
4 5 1 2
Output: 1, 5, 12
Answer
I don't remember where I saw this problem. If I remember I will update the labels.
I am still struggling with editing my layout. I would like to show the labels rather than the archive.
If you know how to do it, please, leave a comment. It will be a true win-win.
Time complexity : $ (N)$
Space complexity: $O(N)$
Here is the C++ source
UPDATE(2019-07-31): Solved the problem in python. I wrote the code quickly but got the test cases wrong. Took too long to find that bug after adding two print statements.
Practice statistics
7:00: to come up with an algorithm
13:00: to write up the code and test code (no bug)
07:00: to find the bug in the test code. (building the tree was wrong).
Total: 26:20
UPDATE(2022-06-14): solved again with no errors. Used python list as a queue.
04:32: for algorithm and pseudo code
08:18: to write up the code
Comments
Post a Comment