Find the maximum element per level in a BST .?
[1] In O(n) time and O(1) space
[2] In O(logn) time and O(n) space
Edit: The solution posted by @Imposter works fine for [1]
Here is the solution for [1]
private int level = 0;
private int VisitedLevels = -1;
public void findLargestByLevel(AvlNode root)
{
if(root == null) return;
else
{
if(level > VisitedLevels)
{
System.out.println(root.data + " @ Level = " + level);
VisitedLevels++;
}
level++;
findLargestByLevel(root.right);
findLargestByLevel(root.left);
level--;
}
}
but I am still not able to work out a solution for [2]
The approaches that I have thought : If we preprocess the tree and flatten it like serialization of the tree,
100
50 200
20 75
#L0, 100, #L1, 50, 200, #L2, 20, 75, #L3
Where the #L is a marker for the levels:
then we can easily answer the queries for the level’s highest and lowest in O(1) time,
Also if the tree get modified we can perform the insertion and deletion from the serialized data in LogN time.
Please suggest someone for the [2], though in my opinion zit looks impossible to achieve [2] but I would like hear other’s suggestions
If the BST is Full BST then it can be done in log(N) time because all you need to do is traverse towards right all the time (since elements on right side are always grater than left side.) If it is not full BST then we have to traverse all the elements because we are not sure that height of right sub tree is always greater than left sub tree.
Example : If right sub tree has two level and left sub tree has three levels then using above approach we are able to print max value till two level but we missed out third level which is not present in right sub tree .
So time complexity will be minimum O(n) if it is not Full BST and may be more if no extra space is given .
If you do BFS it takes only O(n) time complexity and O(n) space complexity . If you want it using DFS then following algorithm would help you in O(n) time complexity and and O(h) where h is height of tree .
Take global variable counter which indicates max number of levels so far while traversing .
Take two variables L and R when ever you make recursive call to left sub tree increment L
similarly when ever you make recursive call to right sub-tree increment R .
Find maximum of L and R for each node which gives level number .
When ever there is increment in max(L,R) for a node while traversing check this with counter if counter is less than max(L,R) then allocate memory and intialize to zero and increment counter.(That means we are actually creating variable for each level in tree).
while traversing we will check for height or level variable every time and compare it with present node that is being considered if present node is bigger than Level variable then update level variable with node that is being considered .
After traversal print height or level variables .