Prerequisite: Tree Traversals (Inorder, Preorder and Postorder), Median
Given a Binary tree having integral nodes, the task is to find the median for each position in the preorder, postorder and inorder traversal of the tree.
The median array is given as the array formed with the help of PreOrder, PostOrder, and Inorder traversal of a tree, such thatÂ
med[i] = median(preorder[i], inorder[i], postorder[i])
Examples:Â
Input: Tree = 1 / \ 2 3 / \ 4 5 Output: {4, 2, 4, 3, 3} Explanation: Preorder traversal = {1 2 4 5 3} Inorder traversal = {4 2 5 1 3} Postorder traversal = {4 5 2 3 1} median[0] = median(1, 4, 4) = 4 median[1] = median(2, 2, 5) = 2 median[2] = median(4, 5, 2) = 4 median[3] = median(5, 1, 3) = 3 median[4] = median(3, 3, 1) = 3 Hence, Median array = {4 2 4 3 3} Input: Tree = 25 / \ 20 30 / \ / \ 18 22 24 32 Output: 18 20 20 24 30 30 32
Approach:Â
- First, find the preorder, postorder and inorder traversal of the given binary tree and store them each in a vector.
- Now, for each position from 0 to N, insert the values at that position in each of the traversal arrays into a vector. The vector will be of 3N size.
- Finally, sort this vector, and the median for this position is given by the 2nd element. In this vector, it has 3N elements. Therefore after sorting, the median will be given by the middle element, the 2nd element, in every 3 elements.
Below is the implementation of the above approach:
CPP
// C++ program to Obtain the median // array for the preorder, postorder // and inorder traversal of a binary tree    #include <bits/stdc++.h> using namespace std;    // A binary tree node has data, // a pointer to the left child // and a pointer to the right child struct Node {     int data;     struct Node *left, *right;     Node( int data)     {         this ->data = data;         left = right = NULL;     } };    // Postorder traversal void Postorder(     struct Node* node,     vector< int >& postorder) {     if (node == NULL)         return ;        // First recur on left subtree     Postorder(node->left, postorder);        // then recur on right subtree     Postorder(node->right, postorder);        // now deal with the node     postorder.push_back(node->data); }    // Inorder traversal void Inorder(     struct Node* node,     vector< int >& inorder) {     if (node == NULL)         return ;        // First recur on left child     Inorder(node->left, inorder);        // then print the data of node     inorder.push_back(node->data);        // now recur on right child     Inorder(node->right, inorder); }    // Preorder traversal void Preorder(     struct Node* node,     vector< int >& preorder) {     if (node == NULL)         return ;        // First print data of node     preorder.push_back(node->data);        // then recur on left subtree     Preorder(node->left, preorder);        // now recur on right subtree     Preorder(node->right, preorder); }    // Function to print the any array void PrintArray(vector< int > median) {     for ( int i = 0;          i < median.size(); i++)         cout << median[i] << " " ;        return ; }    // Function to create and print // the Median array void MedianArray( struct Node* node) {     // Vector to store     // the median values     vector< int > median;        if (node == NULL)         return ;        vector< int > preorder,         postorder,         inorder;        // Traverse the tree     Postorder(node, postorder);     Inorder(node, inorder);     Preorder(node, preorder);        int n = preorder.size();     for ( int i = 0; i < n; i++) {            // Temporary vector to sort         // the three values         vector< int > temp;            // Insert the values at ith index         // for each traversal into temp         temp.push_back(postorder[i]);         temp.push_back(inorder[i]);         temp.push_back(preorder[i]);            // Sort the temp vector to         // find the median         sort(temp.begin(), temp.end());            // Insert the middle value in         // temp into the median vector         median.push_back(temp[1]);     }        PrintArray(median);     return ; }    // Driver Code int main() {     struct Node* root = new Node(1);     root->left = new Node(2);     root->right = new Node(3);     root->left->left = new Node(4);     root->left->right = new Node(5);        MedianArray(root);        return 0; } |
Java
// Java program to Obtain the median // array for the preorder, postorder // and inorder traversal of a binary tree import java.io.*; import java.util.*; Â
// A binary tree node has data, // a pointer to the left child // and a pointer to the right child class Node { Â Â int data; Â Â Node left,right; Â Â Node( int item) Â Â { Â Â Â Â data = item; Â Â Â Â left = right = null ; Â Â } } class Tree { Â Â public static Vector<Integer> postorder = new Vector<Integer>(); Â Â public static Vector<Integer> inorder = new Vector<Integer>(); Â Â public static Vector<Integer> preorder = new Vector<Integer>(); Â Â public static Node root; Â
  // Postorder traversal   public static void Postorder(Node node)   {     if (node == null )     {       return ;     } Â
    // First recur on left subtree     Postorder(node.left); Â
    // then recur on right subtree     Postorder(node.right); Â
    // now deal with the node     postorder.add(node.data);   }   // Inorder traversal   public static void Inorder(Node node)   {     if (node == null )     {       return ;     } Â
    // First recur on left child     Inorder(node.left); Â
    // then print the data of node     inorder.add(node.data); Â
    // now recur on right child     Inorder(node.right);        } Â
  // Preorder traversal   public static void Preorder(Node node)   {     if (node == null )     {       return ;     } Â
    // First print data of node     preorder.add(node.data); Â
    // then recur on left subtree     Preorder(node.left); Â
    // now recur on right subtree     Preorder(node.right);   } Â
  // Function to print the any array      public static void PrintArray(Vector<Integer> median)   {     for ( int i = 0 ; i < median.size(); i++)     {       System.out.print(median.get(i) + " " );     }   } Â
  // Function to create and print   // the Median array   public static void MedianArray(Node node)   { Â
    // Vector to store     // the median values     Vector<Integer> median = new Vector<Integer>();     if (node == null )     {       return ;     } Â
    // Traverse the tree     Postorder(node);     Inorder(node);     Preorder(node);     int n = preorder.size();     for ( int i = 0 ; i < n; i++)     { Â
      // Temporary vector to sort       // the three values       Vector<Integer> temp = new Vector<Integer>(); Â
      // Insert the values at ith index       // for each traversal into temp       temp.add(postorder.get(i));       temp.add(inorder.get(i));       temp.add(preorder.get(i)); Â
      // Sort the temp vector to       // find the median       Collections.sort(temp); Â
      // Insert the middle value in       // temp into the median vector       median.add(temp.get( 1 ));     }     PrintArray(median);   } Â
  // Driver Code   public static void main (String[] args)   {     Tree.root = new Node( 1 );     Tree.root.left = new Node( 2 );     Tree.root.right = new Node( 3 );     Tree.root.left.left = new Node( 4 );     Tree.root.left.right = new Node( 5 );     MedianArray(root);   } } Â
// This code is contributed by avanitrachhadiya2155 |
Python3
# Python3 program to Obtain the median # array for the preorder, postorder # and inorder traversal of a binary tree Â
Â
# A binary tree node has data, # a pointer to the left child # and a pointer to the right child class Node:     def __init__( self , x):         self .data = x         self .left = None         self .right = None Â
# Postorder traversal def Postorder(node):     global preorder     if (node = = None ):         return     # First recur on left subtree     Postorder(node.left) Â
    # then recur on right subtree     Postorder(node.right) Â
    # now deal with the node     postorder.append(node.data) Â
# Inorder traversal def Inorder(node):     global inorder     if (node = = None ):         return Â
    # First recur on left child     Inorder(node.left) Â
    # then print the data of node     inorder.append(node.data) Â
    # now recur on right child     Inorder(node.right) Â
# Preorder traversal def Preorder(node): Â Â Â Â global preorder Â
    if (node = = None ):         return Â
    # First print data of node     preorder.append(node.data) Â
    # then recur on left subtree     Preorder(node.left) Â
    # now recur on right subtree     Preorder(node.right) Â
# Function to print the any array def PrintArray(median): Â Â Â Â for i in range ( len (median)): Â Â Â Â Â Â Â Â print (median[i], end = " " ) Â
    return Â
# Function to create and print # the Median array def MedianArray(node): Â Â Â Â global inorder, postorder, preorder Â
    # Vector to store     # the median values     median = [] Â
    if (node = = None ):         return Â
    # Traverse the tree     Postorder(node)     Inorder(node)     Preorder(node) Â
    n = len (preorder) Â
    for i in range (n): Â
        # Temporary vector to sort         # the three values         temp = [] Â
        # Insert the values at ith index         # for each traversal into temp         temp.append(postorder[i])         temp.append(inorder[i])         temp.append(preorder[i]) Â
        # Sort the temp vector to         # find the median         temp = sorted (temp) Â
        # Insert the middle value in         # temp into the median vector         median.append(temp[ 1 ]) Â
    PrintArray(median) Â
# Driver Code if __name__ = = '__main__' : Â Â Â Â preorder, inorder, postorder = [], [], [] Â Â Â Â root = Node( 1 ) Â Â Â Â root.left = Node( 2 ) Â Â Â Â root.right = Node( 3 ) Â Â Â Â root.left.left = Node( 4 ) Â Â Â Â root.left.right = Node( 5 ) Â
    MedianArray(root) Â
# This code is contributed by mohit kumar 29 |
C#
// C# program to Obtain the median // array for the preorder, postorder // and inorder traversal of a binary tree using System; using System.Collections.Generic; using System.Numerics; Â
// A binary tree node has data, // a pointer to the left child // and a pointer to the right child public class Node { Â Â public int data; Â Â public Node left,right; Â Â public Node( int item) Â Â { Â Â Â Â data = item; Â Â Â Â left = right = null ; Â Â } } public class Tree{ Â Â static List< int > postorder = new List< int >(); Â Â static List< int > inorder = new List< int >(); Â Â static List< int > preorder = new List< int >(); Â
  static Node root;   // Postorder traversal   public static void Postorder(Node node)   {     if (node == null )     {       return ;     } Â
    // First recur on left subtree     Postorder(node.left); Â
    // then recur on right subtree     Postorder(node.right); Â
    // now deal with the node     postorder.Add(node.data);   }   // Inorder traversal   public static void Inorder(Node node)   {     if (node == null )     {       return ;     } Â
    // First recur on left child     Inorder(node.left); Â
    // then print the data of node     inorder.Add(node.data); Â
    // now recur on right child     Inorder(node.right);        }   // Preorder traversal   public static void Preorder(Node node)   {     if (node == null )     {       return ;     } Â
    // First print data of node     preorder.Add(node.data); Â
    // then recur on left subtree     Preorder(node.left); Â
    // now recur on right subtree     Preorder(node.right);   } Â
  // Function to print the any array      public static void PrintArray(List< int > median)   {     for ( int i = 0; i < median.Count; i++)     {       Console.Write(median[i] + " " );     }   } Â
  // Function to create and print   // the Median array   public static void MedianArray(Node node)   { Â
    // Vector to store     // the median values     List< int > median = new List< int >();     if (node == null )     {       return ;     } Â
    // Traverse the tree     Postorder(node);     Inorder(node);     Preorder(node);     int n = preorder.Count;     for ( int i = 0; i < n; i++)     { Â
      // Temporary vector to sort       // the three values       List< int > temp = new List< int >(); Â
      // Insert the values at ith index       // for each traversal into temp       temp.Add(postorder[i]);       temp.Add(inorder[i]);       temp.Add(preorder[i]); Â
      // Sort the temp vector to       // find the median       temp.Sort(); Â
      // Insert the middle value in       // temp into the median vector       median.Add(temp[1]);     }     PrintArray(median);   } Â
  // Driver code   static public void Main ()   {     Tree.root = new Node(1);     Tree.root.left = new Node(2);     Tree.root.right = new Node(3);     Tree.root.left.left = new Node(4);     Tree.root.left.right = new Node(5);     MedianArray(root);   } } Â
// This code is contributed by rag2127 |
Javascript
<script> Â
// JavaScript program to Obtain the median // array for the preorder, postorder // and inorder traversal of a binary tree Â
// A binary tree node has data, // a pointer to the left child // and a pointer to the right child class Node { Â Â Â Â constructor(item) Â Â Â Â { Â Â Â Â Â Â Â Â this .data = item; Â Â Â Â Â Â Â Â this .left = this .right = null ; Â Â Â Â } } Â
let postorder = []; let inorder = []; let preorder = []; Â
// Postorder traversal function Postorder(node) {     if (node == null )     {       return ;     }       // First recur on left subtree     Postorder(node.left);       // then recur on right subtree     Postorder(node.right);       // now deal with the node     postorder.push(node.data); } Â
// Inorder traversal function Inorder(node) {     if (node == null )     {       return ;     }       // First recur on left child     Inorder(node.left);       // then print the data of node     inorder.push(node.data);       // now recur on right child     Inorder(node.right);  } Â
// Preorder traversal function Preorder(node) {     if (node == null )     {       return ;     }       // First print data of node     preorder.push(node.data);       // then recur on left subtree     Preorder(node.left);       // now recur on right subtree     Preorder(node.right); } // Function to print the any array function PrintArray(median) {     for (let i = 0; i < median.length; i++)     {       document.write(median[i] + " " );     } } Â
// Function to create and print   // the Median array function MedianArray(node) {     // Vector to store     // the median values     let median = [];     if (node == null )     {       return ;     }       // Traverse the tree     Postorder(node);     Inorder(node);     Preorder(node);     let n = preorder.length;     for (let i = 0; i < n; i++)     {         // Temporary vector to sort       // the three values       let temp = [];         // Insert the values at ith index       // for each traversal into temp       temp.push(postorder[i]);       temp.push(inorder[i]);       temp.push(preorder[i]);         // Sort the temp vector to       // find the median       temp.sort( function (a,b){ return a-b;});         // Insert the middle value in       // temp into the median vector       median.push(temp[1]);     }     PrintArray(median); } Â
 // Driver Code let root = new Node(1); root.left = new Node(2); root.right = new Node(3); root.left.left = new Node(4); root.left.right = new Node(5); MedianArray(root);          // This code is contributed by patel2127 Â
</script> |
4 2 4 3 3
Â
Time Complexity: O(N)
Auxiliary Space: O(N) as vectors has been created for storing preorder, inorder and postorder traversal of the tree.
Ready to dive in? Explore our Free Demo Content and join our DSA course, trusted by over 100,000 neveropen!