Open In App

Find maximum and minimum element in binary tree without using recursion or stack or queue

Last Updated : 04 Aug, 2021
Summarize
Comments
Improve
Suggest changes
Share
4 Likes
Like
Report

Given a binary tree. The task is to find out the maximum and minimum element in a binary tree without using recursion or stack or queue i.e, space complexity should be O(1). 

Examples: 

Input : 
                       12
                     /     \
                   13       10
                          /     \
                       14       15
                      /   \     /  \
                     21   24   22   23

Output : Max element : 24
         Min element : 10

Input : 
                       12
                     /     \
                  19        82
                 /        /     \
               41       15       95
                 \     /         /  \
                  2   21        7   16

Output : Max element : 95
         Min element : 2

Prerequisite : Inorder Tree Traversal without recursion and without stack

Approach : 
1. Initialize current as root 
2. Take to variable max and min 
3. While current is not NULL 

  • If the current does not have left child 
    • Update variable max and min with current’s data if required
    • Go to the right, i.e., current = current->right
  • Else 
    • Make current as the right child of the rightmost 
      node in current's left subtree
    • Go to this left child, i.e., current = current->left

Below is the implementation of the above approach :  

C++
Java Python3 C# JavaScript

Output : 

Max Value is : 25
Min Value is : 3

Time Complexity: O(N)
Space complexity: O(1)
 


Article Tags :

Similar Reads