Today, we will be looking at the following problem listed as hard with an acceptance rate of 38.6% at the time of writing.
The problem goes as follows:
rootof a binary tree, calculate the vertical order traversal of the binary tree.
For each node at position
(row, col), its left and right children will be at positions
(row + 1, col - 1)and
(row + 1, col + 1)respectively. The root of the tree is at
The vertical order traversal of a binary tree is a list of top-to-bottom orderings for each column index starting from the leftmost column and ending on the rightmost column. There may be multiple nodes in the same row and same column. In such a case, sort these nodes by their values.
Return the vertical order traversal of the binary tree.
Here is my solution:
First of all, I transverse the entire binary tree once, collecting data on the x and y coordinates, and values. For each node, I push the data onto
coordArray using the function
Next, I put that array through a sorting algorithm that sorts according to the following criteria in the given order:
- If x and y of two arrays are the same, sort by value.
- Else if x are the same, sort by y coordinates.
- Else sort by x coordinates.
With my results, I formed a result array called
res which has the first item within it being the value of the first node in
A final loop was performed, starting with the second item within
coordArray which checks if the x values of each nested array is the same. If they are the same, the nested array’s value will be pushed to the last nested array of
res. Else, a new nested array will be pushed into
res with the value within.
And with that, the returned
res array would return the solution the problem. The solution has a time complexity of O(n), and a space complexity of O(n). It has a runtime that beats 66.58% of submissions and a memory usage that beats 39.73% of submissions.