Print vertical sum of a binary tree
All Answers
total answers (1)
Severity: 8192
Message: str_replace(): Passing null to parameter #3 ($subject) of type array|string is deprecated
Filename: libraries/Filtered_db.php
Line Number: 23
total answers (1)
First we need to understand what vertical sum is. Let go through an example to understand what vertical sum is.
For the above tree, let's check what the vertical sum is for the tree.
Just consider, we have partitioned the tree nodes into column & rows where rows are the level no starting from 0. Then the above tree can be converted into the above table easily.
Then column of next node=column of current node-1
Else
Column of next node=column of current node+1
Using the above steps the tree can be easily partitioned to the table. It is to observe that there may be several entry at a specific (row, column) position. Like here, at Level3, column no 1 has two entry 4 & 11.
Rest is about doing sums for each column and printing it.
Thus the vertical sum output should be 2, 12, 8, 20, 9 (from col -2 to col 2 direction).
Though the visual description seems to be very easy to solve this problem, in programing view it’s not that easy.
Algorithm to find vertical sum
The basic concept is to do pre-order traversal & while traversing we will keep track for each column (hashing)& will find cumulative sum.
Thus the column is used as key & we need a map to process our algorithm.
Call vertical_sum(root, 0, hash);
C++ implementation to print vertical sum of a binary tree
Output
need an explanation for this answer? contact us directly to get an explanation for this answer