Median of BST | Practice | GeeksforGeeks

Given a Binary Search Tree of size N, find the Median of its Node values.
Example 1:
Input:
       6
     /   \
   3      8   
 /  \    /  \
1    4  7    9
Output: 6
Explanation: Inorder of Given BST will be:
1, 3, 4, 6, 7, 8, 9. So, here median will 6.


Example 2:
Input:
       6
     /   \
   3      8   
 /   \    /   
1    4   7   
Output: 5
Explanation:Inorder of Given BST will be:
1, 3, 4, 6, 7, 8. So, here median will
(4 + 6)/2 = 10/2 = 5.
 
Your Task:
You don't need to read input or print anything. Your task is to complete the function findMedian() which takes the root of the Binary Search Tree as input and returns the Median of Node values in the given BST.
Median of the BST is:
If number of nodes are even: then median = (N/2 th node + (N/2)+1 th node)/2
If number of nodes are odd : then median = (N+1)/2th node.

Expected Time Complexity: O(N).
Expected Auxiliary Space: O(Height of the Tree).

Constraints:
1<=N<=1000
 
0
ankushkhatri3 days ago
import math

def inorder(root):
    global arr
    if not root:
        return 
    inorder(root.left)
    arr.append(root.data)
    inorder(root.right)
    
def findMedian(root):
    global arr
    arr = []
    inorder(root)
    #print(arr)

    m = int(len(arr)/2)
    n = len(arr)
    if n%2 == 0:
        ans = (arr[m]+arr[m-1])/2
        if math.floor(ans)==math.ceil(ans):
            return int(ans)
        else:
            return ans
    else:
        return arr[m]
0
ankushkhatri
This comment was deleted.
0
uttarandas5012 weeks ago
void inorder(Node *root, vector<int> &v){
    if(!root){return;}
    inorder(root->left, v);
    v.push_back(root->data);
    inorder(root->right, v);
}

float findMedian(struct Node *root)
{
    //Code here
    vector<int>v;
    inorder(root, v);
    return (v[v.size()/2] + v[(v.size()-1)/2])/2.00;
}
0
neerajchatterjee23012 weeks ago
void inorder(struct Node* root, int &n){
    
    if(root == NULL) return;
    
    inorder(root->left, n);
    n++;
    inorder(root->right, n);
    
}

void calc(Node* root, int &k, int &ans){
    
    
    if(root == NULL){
        return;
    }
    
    calc(root->left, k, ans);
    k--;
    if(k == 0){
        
        k = INT_MAX;
        ans = root->data;
        return;
        
    }
    calc(root->right, k, ans);
    
}

float findMedian(struct Node *root)
{
      int n = 0;
      inorder(root, n);
      
      if(n&1){
          int k = (n+1)/2;
          int fans;
          calc(root, k, fans);
          return fans;
      }
      else{
          int k = n/2;
          
          int first;
          calc(root, k, first);
          
          int k2 = n/2 + 1;
         
          int second;
          calc(root, k2, second);
          
          float ans = (first + second) / 2.0 ;
          return ans;
      }
      
}

0
amarrajsmart1972 weeks ago
void inorder(struct Node* root,vector<int> &v){   if(!root)   {       return ;   }   inorder(root->left,v);   v.push_back(root->data);   inorder(root->right,v);}float findMedian(struct Node *root){     //Code here     vector<int> v;     inorder(root,v);     int mid=v.size()/2;     if(v.size()%2==0)     return (v[mid]+v[mid-1])/(float)2;     else     return v[mid];}
0
himanshibaranwal051291 month ago
I am not sure why is this not getting submitted.
 
public static List<Integer> nodeValues = new ArrayList<Integer>();   public static float findMedian(Node root)   {       if(root==null){          return 0;        }              inOrderTraversal(root);              int size = nodeValues.size();              if(size%2==0){           float sumMidValues = nodeValues.get(size/2)+nodeValues.get((size/2)-1);           float median = sumMidValues/2;           return median;       }else{           return nodeValues.get(size/2);       }   }      static void inOrderTraversal(Node root){       if(root==null){           return;       }              inOrderTraversal(root.left);       nodeValues.add(root.data);       inOrderTraversal(root.right);   }
0
harrypotter01 month ago
ans = []def solve(root, ans, count):   if not root:       return    count[0]+=1   solve(root.left, ans,count )   ans.append(root.data)   solve(root.right, ans, count)
   def findMedian(root):   ans = []   count = [0]   solve(root, ans, count )   n = count[0]   # print(ans)   if n%2: ## odd       ind = n//2+1       return ans[ind-1]   else:       ind = (n//2+(n//2)+1)//2       if (ans[n//2-1]+ans[n//2])/2 == int((ans[n//2-1]+ans[n//2])/2):           return int((ans[n//2-1]+ans[n//2])/2)       else:           return (ans[n//2-1]+ans[n//2])/2 
0
cshubham4391 month ago
java Solution
static void inorder(Node root,ArrayList<Integer> list){
       if(root!=null){
           inorder(root.left,list);
           list.add(root.data);
           inorder(root.right,list);
       }
   }
    public static float findMedian(Node root)
    {
        // code here.
      
       ArrayList<Integer> list = new ArrayList<>();
       inorder(root,list);
       int n = list.size();
       if(n%2==0){
           return (((float)list.get(n/2-1)+(float)list.get(n/2))/2);
       }
       else
       return list.get(n/2);
+3
bruhmantri2 months ago
Time Complexity: O(n)
Space Complexity: O(1)  (if recurive stack space not considered)
 
Approach:
First Calculate total numberof nodes in the tree
If the nodes are even, we need to consider 2 numbers for median
If the nodes are odd, only 1 number is needed.
So we find middle element by countOfNodes/2 + 1
We also maintain a prev pointer whcih stores prev traversed node
When our node is at position middleELement, we check if it had even, if yes then we would take prev and root (prev + root)/2 as answer, else we would have just just root as ans
 
int findCountOfNodes(Node *root)
{
    if(!root)
    {
        return 0;
    }
    int leftTree = findCountOfNodes(root->left);
    int rightTree = findCountOfNodes(root->right);
    
    return leftTree + rightTree + 1;
}

void solve(Node* root, int k, bool twoNums, float &ans, int &currentNode, Node* &prev)
{
    if(!root)
    {
        return;
    }
    
    solve(root->left, k, twoNums, ans, currentNode, prev);
    if(currentNode == k)
    {
        if(twoNums)
        {
            ans = ((float)prev->data + (float)root->data)/2;
        }
        else
        {
            ans = root->data;
        }
        
    }
    prev = root;
    currentNode++;
    solve(root->right, k, twoNums, ans, currentNode, prev);
}

float findMedian(struct Node *root)
{
      //Code here
      int countOfNodes = findCountOfNodes(root);
      int currentNode = 1;
      
      bool twoNums = true;
      int k = 0;
      
      if(countOfNodes%2 == 0)
      {
          twoNums = true;
      }
      else
      {
          twoNums = false;
      }
      k = (countOfNodes/2) + 1;
      
      float ans = 0;
      Node* prev = NULL;
      solve(root, k, twoNums, ans, currentNode, prev);
      
      return ans;
}
0
yojobex113
This comment was deleted.
We strongly recommend solving this problem on your own before viewing its editorial. Do you still
                    want to view the editorial?
 Login to access your submissions. 

Problem


Contest

Reset the IDE using the second button on the top right corner.
Avoid using static/global variables in your code as your code is tested against multiple test cases and these tend to retain their previous values.
Passing the Sample/Custom Test cases does not guarantee the correctness of code. On submission, your code is tested against multiple test cases consisting of all possible corner cases and stress constraints.
You can access the hints to get an idea about what is expected of you as well as the final solution code.
You can view the solutions submitted by other users from the submission tab.