Binary Tree Miscellaneous
Binary Tree Miscellaneous
- Method 1: Find preorder; save it; create list based on that preorder
- Method 2: Use modified Morris preorder traversal to optimise/ have constant space
Idea is to attach the predecessor to the parent’s right WHICH MEANS attaching the last
node explored in left subtree to the first node explored in right subtree(as per preorder
traversal)
- Method 1: Save the numbers in a list as they come; and recompute the median each
time the findMedian() function is called.
Recomputation involves, 1. Sort the list, 2. According to the number of elements, finding
the median index/ avg of middle values(if even)
- Method 2: Keeping track of middle elements of the stream as the data is added each
time, it would optimise the solution.
Maintain a max heap for the left half of the data, and a min heap for the right half of the
data. The max heap stores the maximum element in the left portion(thus the rightmost
extreme element) and the min heap stores the minimum element in the right portion(thus
the leftmost extreme element)
After each addition of an element, we should balance the heaps such that the difference
between the sizes is not greater than one. Since that would lose the middle element if
the parts were not correctly partitioned.
Time complexity: O(log n) for adding an element +O(log n) for balance function + O(1)
for computing median
Space complexity: O(n) overall since two halves of the data stream is maintained in two
different heaps.
Space is O(log K)
- Check If Subtree:
Check if given 2 root nodes, the S tree is a subset of the T tree.
Inorder morris traversal with slight modifications can implement this algorithm in O(1) space and
O(n) space since we visit the nodes at most two times in this traversal.
Method 2: Can store the inorder traversal, and create a DLL from these values. Extra space
complexity involved here.
Given a window size, calculate the number of distinct numbers in all windows of given size.
Optimal approach:
Instead of recomputing for every window, we can simply use the previous results to simplify the
process. A sliding technique is used here such that when we are moving to the next window, we
remove the previous element from the tracker(a map) and add the new element to it. Then we
can calculate the map size to get the distinct elements.
This approach involves iterating over the array once and additional space depending on the
window size.
If window size is K, the space complexity will be O(K)
And the time complexity will be: O(N) where N is the size of the array.