![]() |
VOOZH | about |
Given a Binary Tree, find the maximum(or minimum) element in it. For example, maximum in the following Binary Tree is 9.
In Binary Search Tree, we can find maximum by traversing right pointers until we reach the rightmost node. But in Binary Tree, we must visit every node to figure out maximum. So the idea is to traverse the given tree and for every node return maximum of 3 values.
Below is the implementation of above approach.
Maximum element is 11
Time Complexity: O(N), where N is number of nodes as every node of tree is traversed once by findMax() and findMin().
Auxiliary Space: O(N) , Recursive call for each node tree considered as stack space.
Similarly, we can find the minimum element in a Binary tree by comparing three values. Below is the function to find a minimum in Binary Tree.
Time Complexity: O(N).
In the recursive function calls, every node of the tree is processed once and hence the complexity due to the function is O(N) if there are total N nodes in the tree. Therefore, the time complexity is O(N).
Space Complexity: O(N).
Recursive call is happening. The every node is processed once and considering the stack space, the space complexity will be O(N).