Open In App

Basic Operations on Binary Tree with Implementations

Last Updated : 16 Apr, 2024
Improve
Improve
Like Article
Like
Save
Share
Report

The tree is a hierarchical Data Structure. A binary tree is a tree that has at most two children. The node which is on the left of the Binary Tree is called “Left-Child” and the node which is the right is called “Right-Child”. Also, the smaller tree or the subtree in the left of the root node is called the “Left sub-tree” and that is on the right is called “Right sub-tree”.

Tree

Below are the various operations that can be performed on a Binary Tree:

Creation of Binary Tree:

The idea is to first create the root node of the given tree, then recursively create the left and the right child for each parent node. Below is the program to illustrate the same:

C++
// C++ program to illustrate how to
// create a tree
#include <iostream>
using namespace std;

// Structure of the Binary Tree
struct treenode {
    int info;
    struct treenode *left,
        *right;
};

// Function to create the Binary Tree
struct treenode* create()
{
    int data;
    struct treenode* tree;

    // Dynamically allocating memory
    // for the tree-node
    tree = new treenode;

    cout << "\nEnter data to be inserted "
         << "or type -1 for no insertion : ";

    // Input from the user
    cin >> data;

    // Termination Condition
    if (data == -1)
        return 0;

    // Assign value from user into tree
    tree->info = data;

    // Recursively Call to create the
    // left and the right sub tree
    cout << "Enter left child of : "
         << data;
    tree->left = create();

    cout << "Enter right child of : "
         << data;
    tree->right = create();

    // Return the created Tree
    return tree;
};

// Function to perform the inorder
// traversal of the given Tree
void inorder(struct treenode* root)
{
    // If root is NULL
    if (root == NULL)
        return;

    // Recursively call for the left
    // and the right subtree
    inorder(root->left);
    cout << root->info << "  ";
    inorder(root->right);
}

// Driver Code
int main()
{
    // Root Node
    struct treenode* root = NULL;

    // Function Call
    root = create();

    // Perform Inorder Traversal
    inorder(root);

    return 0;
}

/* Will be creating tree:
                2  
           /     \  
          7       5  
         /  \       \  
        2    6       9
 */
Java
import java.util.Scanner;
// class of the Binary Tree node

class TreeNode {
    int info;
    TreeNode left, right;

    TreeNode(int data) {
        this.info = data;
        left = right = null;
    }
}

class GFG {
    static Scanner sc = new Scanner(System.in);
// Function to create the Binary Tree

    static TreeNode create() {
        int data;
        System.out.print("\nEnter data to be inserted or type -1 for no insertion : ");
        data = sc.nextInt();
        if (data == -1) {
            return null;
        }
        TreeNode tree = new TreeNode(data);
        System.out.print("Enter left child of : " + data);
        tree.left = create();
        System.out.print("Enter right child of : " + data);
        tree.right = create();
        return tree;
    }
    // Perform Inorder Traversal

    static void inorder(TreeNode root) {
        if (root == null) {
            return;
        }
        inorder(root.left);
        System.out.print(root.info + " ");
        inorder(root.right);
    }
// Driver Code

    public static void main(String[] args) {
        TreeNode root = null;
        root = create();
        inorder(root);
    }
}
Python3
#Python equivalent

# Class of the Binary Tree node
class TreeNode:
    def __init__(self, data):
        self.info = data
        self.left = None
        self.right = None

# Function to create the Binary Tree
def create():
    data = int(input("\nEnter data to be inserted or type -1 for no insertion : "))
    if data == -1:
        return None
    tree = TreeNode(data)
    print("Enter left child of : " + str(data))
    tree.left = create()
    print("Enter right child of : " + str(data))
    tree.right = create()
    return tree

# Perform Inorder Traversal
def inorder(root):
    if root == None:
        return
    inorder(root.left)
    print(root.info, end=" ")
    inorder(root.right)

# Driver Code
if __name__ == '__main__':
    root = None
    root = create()
    inorder(root)
C#
// C# program to illustrate how to
// create a tree
using System;

// Structure of the Binary Tree
public class treenode {
    public int info;
    public treenode left, right;

    public treenode()
    {
        info = 0;
        left = null;
        right = null;
    }
}

// Class to perform the operations
public class GFG {
    // Function to create the Binary Tree
    public static treenode create()
    {
        int data;
        treenode tree = new treenode();

        Console.WriteLine(
            "\nEnter data to be inserted "
            + "or type -1 for no insertion : ");

        // Input from the user
        data = Convert.ToInt32(Console.ReadLine());

        // Termination Condition
        if (data == -1)
            return null;

        // Assign value from user into tree
        tree.info = data;

        // Recursively Call to create the
        // left and the right sub tree
        Console.WriteLine("Enter left child of : " + data);
        tree.left = create();

        Console.WriteLine("Enter right child of : " + data);
        tree.right = create();

        // Return the created Tree
        return tree;
    }

    // Function to perform the inorder
    // traversal of the given Tree
    public static void inorder(treenode root)
    {
        // If root is NULL
        if (root == null)
            return;

        // Recursively call for the left
        // and the right subtree
        inorder(root.left);
        Console.Write(root.info + "  ");
        inorder(root.right);
    }

    // Driver Code
    public static void Main()
    {
        // Root Node
        treenode root = null;

        // Function Call
        root = create();

        // Perform Inorder Traversal
        inorder(root);
    }
}

/* Will be creating tree:
                2
           /     \
          7       5
         /  \       \
        2    6       9
 */
Javascript
// javascript program to illustrate how to
// create a tree

// Structure of the Binary Tree
class treenode {
    
    constructor(){
        this.info = 0;
        this.left = null;
        this.right = null;
    }
}

// Function to create the Binary Tree
function create()
{
    let data;
    let tree = new treenode();



    // Input from the user
    // data = readInt("\n Enter data to be inserted or type -1 for no insertion :");
    data = prompt("\n Enter data to be inserted or type -1 for no insertion :");


    // Termination Condition
    if (data == -1)
        return 0;

    // Assign value from user into tree
    tree.info = data;

    // Recursively Call to create the
    // left and the right sub tree
    console.log("Enter left child of : " + data);
    tree.left = create();

    console.log("Enter right child of : " + data);
    tree.right = create();

    // Return the created Tree
    return tree;
}

// Function to perform the inorder
// traversal of the given Tree
function inorder(root)
{
    // If root is NULL
    if (root == null)
        return;

    // Recursively call for the left
    // and the right subtree
    inorder(root.left);
    console.log(root.info);
    inorder(root.right);
}

// Driver Code
// Root Node
let root = null;

// Function Call
root = create();

// Perform Inorder Traversal
inorder(root);

/* Will be creating tree:
                2  
           /     \  
          7       5  
         /  \       \  
        2    6       9
 */

// The code is contributed by Nidhi goel. 

Output:

Tree creation

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

Pre-order Traversal:

In this traversal, the root is visited first followed by the left and the right subtree. Below is the program to illustrate the same:

C++
// C++ program to demonstrate the
// pre-order traversal
#include "bits/stdc++.h"
using namespace std;

// Structure of the Binary Tree
struct treenode {
    int info;
    struct treenode *left,
        *right;
};

// Function to create the Binary Tree
struct treenode* create()
{
    int data;
    struct treenode* tree;

    // Dynamically allocating memory
    // for the tree-node
    tree = new treenode;

    cout << "\nEnter data to be inserted "
         << "or type -1 for no insertion : ";

    // Input from the user
    cin >> data;

    // Termination Condition
    if (data == -1)
        return 0;

    // Assign value from user into tree
    tree->info = data;

    // Recursively Call to create the
    // left and the right sub tree
    cout << "Enter left child of : "
         << data;
    tree->left = create();

    cout << "Enter right child of : "
         << data;
    tree->right = create();

    // Return the created Tree
    return tree;
};

// Function to perform the pre-order
// traversal for the given tree
void preorder(struct treenode* root)
{
    // If the root is NULL
    if (root == NULL)
        return;

    // Using tree-node type stack STL
    stack<treenode*> s;

    while ((root != NULL) || (!s.empty())) {
        if (root != NULL) {
            // Print the root
            cout << root->info << " ";

            // Push the node in the stack
            s.push(root);

            // Move to left subtree
            root = root->left;
        }
        else {
            // Remove the top of stack
            root = s.top();
            s.pop();
            root = root->right;
        }
    }

    cout << endl;
}

// Driver Code
int main()
{
    // Root Node
    struct treenode* root = NULL;

    // Function Call
    root = create();

    // Perform Inorder Traversal
    preorder(root);

    return 0;
}

/* Will be creating tree:
                2  
           /     \  
          7       5  
         /  \       \  
        2    6       9
 */
Java
import java.io.*;
import java.util.Scanner;
import java.util.Stack;

class TreeNode {
    int info;
    TreeNode left;
    TreeNode right;
    
    // Constructor
    TreeNode(int info) {
        this.info = info;
        left = null;
        right = null;
    }
}

class GFG {
    
    // Function to create a binary tree
    public static TreeNode create() {
        Scanner scanner = new Scanner(System.in);
        System.out.print("Enter data to be inserted or type -1 for no insertion: ");
        int data = scanner.nextInt();
        
        // Termination condition
        if (data == -1)
            return null;
        
        TreeNode tree = new TreeNode(data);
        
        System.out.print("Enter left child of " + data + ": ");
        tree.left = create();
        
        System.out.print("Enter right child of " + data + ": ");
        tree.right = create();
        
        return tree;
    }
    
    // Function to perform pre-order traversal of a binary tree
    public static void preorder(TreeNode root) {
        if (root == null)
            return;
        
        Stack<TreeNode> stack = new Stack<>();
        stack.push(root);
        
        while (!stack.isEmpty()) {
            TreeNode current = stack.pop();
            System.out.print(current.info + " ");
            
            if (current.right != null)
                stack.push(current.right);
            
            if (current.left != null)
                stack.push(current.left);
        }
        
        System.out.println();
    }
    
    public static void main(String[] args) {
        // Root Node
        TreeNode root = null;
        
        // Function Call to create the binary tree
        root = create();
        
        // Perform pre-order traversal
        preorder(root);
    }
}

/* Will be creating tree:
                2  
           /     \  
          7       5  
         /  \       \  
        2    6       9
 */
Python3
# Python code addition 

# Structure of the Binary Tree
class TreeNode:
    def __init__(self, val=0, left=None, right=None):
        self.val = val
        self.left = left
        self.right = right

# Function to create the Binary Tree
def create():
    data = int(input("\nEnter data to be inserted or type -1 for no insertion: "))

    # Termination Condition
    if data == -1:
        return None

    # Assign value from user into tree
    root = TreeNode(data)

    # Recursively Call to create the left and the right sub tree
    print("Enter left child of:", data)
    root.left = create()

    print("Enter right child of:", data)
    root.right = create()

    # Return the created Tree
    return root

# Function to perform the pre-order traversal for the given tree
def preorder(root):
    # If the root is None
    if not root:
        return
    
    # Using tree-node type stack STL
    stack = []

    while root or stack:
        if root:
            # Print the root
            print(root.val, end=" ")

            # Push the node in the stack
            stack.append(root)

            # Move to left subtree
            root = root.left
        else:
            # Remove the top of stack
            root = stack.pop()
            root = root.right

    print()

# Driver Code
if __name__ == "__main__":
    # Root Node
    root = None

    # Function Call
    root = create()

    # Perform Pre-order Traversal
    preorder(root)

# The code is contributed by Nidhi goel. 
C#
using System;
using System.Collections.Generic;

class TreeNode
{
    public int info;
    public TreeNode left;
    public TreeNode right;

    // Constructor
    public TreeNode(int info)
    {
        this.info = info;
        left = null;
        right = null;
    }
}

class GFG
{
    // Function to create a binary tree
    public static TreeNode Create()
    {
        Console.Write("Enter data to be inserted or type -1 for no insertion: ");
        int data = Convert.ToInt32(Console.ReadLine());

        // Termination condition
        if (data == -1)
            return null;

        TreeNode tree = new TreeNode(data);

        Console.Write("Enter left child of " + data + ": ");
        tree.left = Create();

        Console.Write("Enter right child of " + data + ": ");
        tree.right = Create();

        return tree;
    }

    // Function to perform pre-order traversal of a binary tree
    public static void Preorder(TreeNode root)
    {
        if (root == null)
            return;

        Stack<TreeNode> stack = new Stack<TreeNode>();
        stack.Push(root);

        while (stack.Count > 0)
        {
            TreeNode current = stack.Pop();
            Console.Write(current.info + " ");

            if (current.right != null)
                stack.Push(current.right);

            if (current.left != null)
                stack.Push(current.left);
        }

        Console.WriteLine();
    }

    public static void Main(string[] args)
    {
        // Root Node
        TreeNode root = null;

        // Function Call to create the binary tree
        root = Create();

        // Perform pre-order traversal
        Preorder(root);
    }
}

// by phasing17
Javascript
class TreeNode {
  constructor(info) {
    this.info = info;
    this.left = null;
    this.right = null;
  }
}

function create() {
  let data = prompt(
    "Enter data to be inserted or type -1 for no insertion : "
  );

  // Termination Condition
  if (data == -1) return null;

  // Assign value from user into tree
  let tree = new TreeNode(data);

  // Recursively Call to create the
  // left and the right sub tree
  tree.left = create();
  tree.right = create();

  // Return the created Tree
  return tree;
}

// Function to perform the pre-order
// traversal for the given tree
function preorder(root) {
  // If the root is NULL
  if (root == null) return;

  // Using tree-node type stack STL
  let s = [];

  while (root != null || s.length > 0) {
    if (root != null) {
      // Print the root
      console.log(root.info);

      // Push the node in the stack
      s.push(root);

      // Move to left subtree
      root = root.left;
    } else {
      // Remove the top of stack
      root = s.pop();
      root = root.right;
    }
  }
}

// Driver Code

// Root Node
let root = null;

// Function Call
root = create();

// Perform Inorder Traversal
preorder(root);

Output:

Pre-order traversal

Time Complexity: O(N)
Auxiliary Space: O(N)

In-order Traversal:

In this traversal, the left subtree is visited first followed by the root and the right subtree. Below is the program to illustrate the same:

C++
// C++ program to illustrate how to
// create a tree
#include "bits/stdc++.h"
using namespace std;

// Structure of the Binary Tree
struct treenode {
    int info;
    struct treenode *left,
        *right;
};

// Function to create the Binary Tree
struct treenode* create()
{
    int data;
    struct treenode* tree;

    // Dynamically allocating memory
    // for the tree-node
    tree = new treenode;

    cout << "\nEnter data to be inserted "
         << "or type -1 for no insertion : ";

    // Input from the user
    cin >> data;

    // Termination Condition
    if (data == -1)
        return 0;

    // Assign value from user into tree
    tree->info = data;

    // Recursively Call to create the
    // left and the right sub tree
    cout << "Enter left child of : "
         << data;
    tree->left = create();

    cout << "Enter right child of : "
         << data;
    tree->right = create();

    // Return the created Tree
    return tree;
};

// Function to perform the inorder
// traversal of the given Tree
void inorder(struct treenode* root)
{
    // If root is NULL
    if (root == NULL)
        return;

    // Recursively call for the left
    // and the right subtree
    inorder(root->left);
    cout << root->info << "  ";
    inorder(root->right);
}

// Driver Code
int main()
{
    // Root Node
    struct treenode* root = NULL;

    // Function Call
    root = create();

    // Perform Inorder Traversal
    inorder(root);

    return 0;
}

/* Will be creating tree:
                2  
           /     \  
          7       5  
         /  \       \  
        2    6       9
 */
Java
import java.util.Scanner;

// Structure of the Binary Tree Node
class TreeNode {
    int info;
    TreeNode left;
    TreeNode right;
}

public class BinaryTreeCreation {

    // Function to create the Binary Tree
    public static TreeNode create() {
        Scanner sc = new Scanner(System.in);
        int data;
        TreeNode tree = new TreeNode();

        System.out.print("Enter data to be inserted or type -1 for no insertion: ");
        data = sc.nextInt();

        // Termination Condition
        if (data == -1) {
            return null;
        }

        // Assign value from user into the tree
        tree.info = data;

        // Recursively create the left and the right sub tree
        System.out.print("Enter left child of " + data + ": ");
        tree.left = create();

        System.out.print("Enter right child of " + data + ": ");
        tree.right = create();

        // Return the created Tree
        return tree;
    }

    // Function to perform the inorder traversal of the given Tree
    public static void inorder(TreeNode root) {
        // If root is null
        if (root == null) {
            return;
        }

        // Recursively call for the left and the right subtree
        inorder(root.left);
        System.out.print(root.info + "  ");
        inorder(root.right);
    }

    public static void main(String[] args) {
        // Root Node
        TreeNode root = null;

        // Function Call to create the binary tree
        root = create();

        // Perform Inorder Traversal
        System.out.print("Inorder Traversal: ");
        inorder(root);
    }
}
Python3
# Structure of the Binary Tree
class TreeNode:
    def __init__(self, info):
        self.info = info
        self.left = None
        self.right = None
# Function to create the Binary Tree
def create():
  
      # Input from the user
    data = int(input("Enter data to be inserted or type -1 for no insertion: "))
    
    # Termination Condition
    if data == -1:
        return None
    
    # Dynamically allocating memory
    # for the tree-node
    # Assign value from user into tree
    tree = TreeNode(data)
    
    
    # Recursively Call to create the
    # left and the right sub tree
    print("Enter left child of:", data)
    tree.left = create()
    
    print("Enter right child of:", data)
    tree.right = create()
    
    
    #  Return the created Tree
    return tree

# Function to perform the inorder
# traversal of the given Tree
def inorder(root):
    # If root is NULL
    if root is None:
        return
    
    # Recursively call for the left
    # and the right subtree
    inorder(root.left)
    print(root.info, end=" ")
    inorder(root.right)

# Driver Code
root = create()
inorder(root)
C#
using System;

// Structure of the Binary Tree
class TreeNode
{
    public int Info;
    public TreeNode Left, Right;

    public TreeNode(int data)
    {
        Info = data;
        Left = Right = null;
    }
}

class BinaryTree
{
    // Function to create the Binary Tree
    static TreeNode CreateTree()
    {
        int data;
        
        Console.Write("\nEnter data to be inserted " +
                      "or type -1 for no insertion: ");
        // Input from the user
        if (!int.TryParse(Console.ReadLine(), out data) || data == -1)
        {
            return null;
        }

        // Assign value from user into tree
        TreeNode tree = new TreeNode(data);

        // Recursively Call to create the
        // left and the right sub tree
        Console.Write("Enter left child of " + data + ": ");
        tree.Left = CreateTree();

        Console.Write("Enter right child of " + data + ": ");
        tree.Right = CreateTree();

        // Return the created Tree
        return tree;
    }

    // Function to perform the inorder
    // traversal of the given Tree
    static void Inorder(TreeNode root)
    {
        // If root is NULL
        if (root == null)
            return;

        // Recursively call for the left
        // and the right subtree
        Inorder(root.Left);
        Console.Write(root.Info + "  ");
        Inorder(root.Right);
    }

    // Driver Code
    static void Main()
    {
        // Root Node
        TreeNode root = null;

        // Function Call
        root = CreateTree();

        // Perform Inorder Traversal
        Inorder(root);
    }
}
Javascript
// JavaScript program to illustrate how to
// create a tree

// Structure of the Binary Tree
class TreeNode {
    constructor(info) {
        this.info = info;
        this.left = null;
        this.right = null;
    }
}

// Function to create the Binary Tree
function create() {
    const tree = new TreeNode();

    let data;
    console.log("Enter data to be inserted or type -1 for no insertion : ");

    // Input from the user
    data = parseInt(prompt());

    // Termination Condition
    if (data === -1)
        return null;

    // Assign value from user into tree
    tree.info = data;

    // Recursively Call to create the
    // left and the right sub tree
    console.log(`Enter left child of ${data}: `);
    tree.left = create();

    console.log(`Enter right child of ${data}: `);
    tree.right = create();

    // Return the created Tree
    return tree;
}

// Function to perform the inorder
// traversal of the given Tree
function inorder(root) {
    // If root is NULL
    if (root == null)
        return;

    // Recursively call for the left
    // and the right subtree
    inorder(root.left);
    console.log(`${root.info} `);
    inorder(root.right);
}

// Driver Code
function main() {
    // Root Node
    let root = null;

    // Function Call
    root = create();

    // Perform Inorder Traversal
    inorder(root);
}

// Invoke the main function
main();

/* Will be creating tree:
             2  
           /   \  
          7     5  
         /  \     \  
        2    6     9
 */

Output:

In-order traversal

Time Complexity: O(N)
Auxiliary Space: O(N)

Post-order Traversal:

In this traversal, the left subtree is visited first, followed by the right subtree and root node. Below is the program to illustrate the same:

C++
// C++ program to implement the
// post-order traversal
#include "bits/stdc++.h"
using namespace std;

// Structure of the Binary Tree
struct treenode {
    int info;
    struct treenode *left,
        *right;
};

// Function to create the Binary Tree
struct treenode* create()
{
    int data;
    struct treenode* tree;

    // Dynamically allocating memory
    // for the tree-node
    tree = new treenode;

    cout << "\nEnter data to be inserted "
         << "or type -1 for no insertion : ";

    // Input from the user
    cin >> data;

    // Termination Condition
    if (data == -1)
        return 0;

    // Assign value from user into tree
    tree->info = data;

    // Recursively Call to create the
    // left and the right sub tree
    cout << "Enter left child of : "
         << data;
    tree->left = create();

    cout << "Enter right child of : "
         << data;
    tree->right = create();

    // Return the created Tree
    return tree;
};

// Function to perform the post-order
// traversal of the given tree
void postorder(struct treenode* root)
{
    // If the root is NULL
    return;

    stack<treenode*> s3;
    struct treenode* previous = NULL;

    do {
        // Iterate until root is present
        while (root != NULL) {
            s3.push(root);
            root = root->left;
        }

        while (root == NULL && (!s3.empty())) {
            root = s3.top();

            // If the right subtree is NULL
            if (root->right == NULL
                || root->right == previous) {
                // Print the root information
                cout << root->info << " ";
                s3.pop();

                // Update the previous
                previous = root;
                root = NULL;
            }

            // Otherwise
            else
                root = root->right;
        }

    } while (!s3.empty());
    cout << endl;
}

// Driver Code
int main()
{
    // Root Node
    struct treenode* root = NULL;

    // Function Call
    root = create();

    // Perform Inorder Traversal
    postorder(root);

    return 0;
}

/* Will be creating tree:
                2  
           /     \  
          7       5  
         /  \       \  
        2    6       9
 */
Java
import java.util.Stack;
import java.util.Scanner;

// Structure of the Binary Tree
class TreeNode {
    int info;
    TreeNode left, right;

    // Constructor
    public TreeNode(int data) {
        info = data;
        left = right = null;
    }
}

class PostOrderTraversal {
    // Function to create the Binary Tree
    public static TreeNode create() {
        Scanner scanner = new Scanner(System.in);
        int data;

        System.out.print("Enter data to be inserted or type -1 for no insertion: ");
        data = scanner.nextInt();

        // Termination Condition
        if (data == -1)
            return null;

        // Create new TreeNode
        TreeNode tree = new TreeNode(data);

        // Recursively Call to create the left and the right sub-tree
        System.out.print("Enter left child of " + data + ": ");
        tree.left = create();

        System.out.print("Enter right child of " + data + ": ");
        tree.right = create();

        // Return the created Tree
        return tree;
    }

    // Function to perform the post-order traversal of the given tree
    public static void postOrder(TreeNode root) {
        // If the root is NULL
        if (root == null)
            return;

        Stack<TreeNode> stack = new Stack<>();
        TreeNode previous = null;

        do {
            // Iterate until root is present
            while (root != null) {
                stack.push(root);
                root = root.left;
            }

            while (root == null && !stack.isEmpty()) {
                root = stack.pop();

                // If the right subtree is NULL
                if (root.right == null || root.right == previous) {
                    // Print the root information
                    System.out.print(root.info + " ");

                    // Update the previous
                    previous = root;
                    root = null;
                } else {
                    root = root.right;
                }
            }

        } while (!stack.isEmpty());
        System.out.println();
    }

    // Driver Code
    public static void main(String[] args) {
        // Root Node
        TreeNode root;

        // Function Call
        root = create();

        // Perform Post-Order Traversal
        postOrder(root);
    }
}
Python3
class TreeNode:
    def __init__(self, data):
        self.info = data
        self.left = None
        self.right = None

def create():
    try:
        user_input = input("Enter data to be inserted or type -1 for no insertion: ").strip()

        if not user_input or user_input == "-1":
            return None

        data = int(user_input)
        tree = TreeNode(data)

        print("Enter left child of {}: ".format(data), end="")
        tree.left = create()

        print("Enter right child of {}: ".format(data), end="")
        tree.right = create()

        return tree
    except ValueError:
        print("Invalid input. Please enter a valid integer.")
        return create()
    except EOFError:
        print("Error reading input. Make sure you are running the script in an environment that supports interactive input.")
        exit(1)

def post_order(root):
    if not root:
        return

    stack = []
    previous = None

    while True:
        while root:
            stack.append(root)
            root = root.left

        while not root and stack:
            root = stack.pop()

            if not root.right or root.right == previous:
                print(root.info, end=" ")
                previous = root
                root = None
            else:
                root = root.right

        if not stack:
            break

    print()

# Driver Code
if __name__ == "__main__":
    # Root Node
    root = None

    # Function Call
    root = create()

    # Perform Post-Order Traversal
    post_order(root)
C#
using System;
using System.Collections.Generic;

// Structure of the Binary Tree
class TreeNode
{
    public int Info;
    public TreeNode Left, Right;

    // Constructor
    public TreeNode(int data)
    {
        Info = data;
        Left = Right = null;
    }
}

class PostOrderTraversal
{
    // Function to create the Binary Tree
    public static TreeNode Create()
    {
        Console.Write("Enter data to be inserted or type -1 for no insertion: ");
        string userInput = Console.ReadLine();

        if (string.IsNullOrEmpty(userInput) || userInput.Trim() == "-1")
            return null;

        try
        {
            int data = Convert.ToInt32(userInput);

            // Create new TreeNode
            TreeNode tree = new TreeNode(data);

            // Recursively Call to create the left and the right sub-tree
            Console.Write($"Enter left child of {data}: ");
            tree.Left = Create();

            Console.Write($"Enter right child of {data}: ");
            tree.Right = Create();

            // Return the created Tree
            return tree;
        }
        catch (FormatException)
        {
            Console.WriteLine("Invalid input. Please enter a valid integer.");
            return Create(); // Retry the input
        }
    }

    // Function to perform the post-order traversal of the given tree
    public static void PostOrder(TreeNode root)
    {
        // If the root is NULL
        if (root == null)
            return;

        Stack<TreeNode> stack = new Stack<TreeNode>();
        TreeNode previous = null;

        do
        {
            // Iterate until root is present
            while (root != null)
            {
                stack.Push(root);
                root = root.Left;
            }

            while (root == null && stack.Count > 0)
            {
                root = stack.Pop();

                // If the right subtree is NULL
                if (root.Right == null || root.Right == previous)
                {
                    // Print the root information
                    Console.Write(root.Info + " ");

                    // Update the previous
                    previous = root;
                    root = null;
                }
                else
                {
                    root = root.Right;
                }
            }

        } while (stack.Count > 0);
        Console.WriteLine();
    }

    // Driver Code
    public static void Main(string[] args)
    {
        // Root Node
        TreeNode root;

        // Function Call
        root = Create();

        // Perform Post-Order Traversal
        PostOrder(root);
    }
}
Javascript
class TreeNode {
    constructor(data) {
        this.info = data;
        this.left = this.right = null;
    }
}

// Function to create the Binary Tree
function create() {
    const readline = require('readline');
    const rl = readline.createInterface({
        input: process.stdin,
        output: process.stdout
    });

    return new Promise((resolve) => {
        rl.question("Enter data to be inserted or type -1 for no insertion: ", (data) => {
            data = parseInt(data);

            // Termination Condition
            if (data === -1) {
                rl.close();
                resolve(null);
            } else {
                // Create new TreeNode
                const tree = new TreeNode(data);

                // Recursively Call to create the left and the right sub-tree
                rl.question("Enter left child of " + data + ": ", (leftChildData) => {
                    create().then((leftChild) => {
                        tree.left = leftChild;

                        rl.question("Enter right child of " + data + ": ", (rightChildData) => {
                            create().then((rightChild) => {
                                tree.right = rightChild;
                                rl.close();
                                resolve(tree);
                            });
                        });
                    });
                });
            }
        });
    });
}

// Function to perform the post-order traversal of the given tree
function postOrder(root) {
    // If the root is NULL
    if (root === null)
        return;

    const stack = [];
    let previous = null;

    do {
        // Iterate until root is present
        while (root !== null) {
            stack.push(root);
            root = root.left;
        }

        while (root === null && stack.length > 0) {
            root = stack.pop();

            // If the right subtree is NULL
            if (root.right === null || root.right === previous) {
                // Print the root information
                process.stdout.write(root.info + " ");

                // Update the previous
                previous = root;
                root = null;
            } else {
                root = root.right;
            }
        }

    } while (stack.length > 0);
    console.log();
}

// Driver Code
async function main() {
    // Root Node
    const root = await create();

    // Perform Post-Order Traversal
    postOrder(root);
}

main();

Output:

post-order traversal

Time Complexity: O(N)
Auxiliary Space: O(N)

Level-order Traversal:

In this traversal, the given tree is traversal level-wise. Below is the program to illustrate the same:

C++
// C++ program to illustrate the
// level order traversal#include "bits/stdc++.h"
using namespace std;

// Structure of the Binary Tree
struct treenode {
    int info;
    struct treenode *left,
        *right;
};

// Function to create the Binary Tree
struct treenode* create()
{
    int data;
    struct treenode* tree;

    // Dynamically allocating memory
    // for the tree-node
    tree = new treenode;

    cout << "\nEnter data to be inserted "
         << "or type -1 for no insertion : ";

    // Input from the user
    cin >> data;

    // Termination Condition
    if (data == -1)
        return 0;

    // Assign value from user into tree
    tree->info = data;

    // Recursively Call to create the
    // left and the right sub tree
    cout << "Enter left child of : "
         << data;
    tree->left = create();

    cout << "Enter right child of : "
         << data;
    tree->right = create();

    // Return the created Tree
    return tree;
};

// Function to perform the level-order
// traversal
void levelorder(struct treenode* root)
{
    // If the root is NULL
    if (root == NULL)
        return;

    // Use queue for traversal
    queue<treenode*> q;

    // Print the root's value and
    // push it into the queue
    cout << root->info << " ";
    q.push(root);

    // Iterate until queue is non-empty
    while (!q.empty()) {
        // Get the front node
        root = q.front();
        q.pop();

        // If the root has the left child
        if (root->left) {
            cout << root->left->info
                 << " ";
            q.push(root->left);
        }

        // If the root has the right child
        if (root->right) {
            cout << root->right->info
                 << " ";
            q.push(root->right);
        }
    }
    cout << endl;
}

// Driver Code
int main()
{
    // Root Node
    struct treenode* root = NULL;

    // Function Call
    root = create();

    // Perform Inorder Traversal
    levelorder(root);

    return 0;
}

/* Will be creating tree:
                2  
           /     \  
          7       5  
         /  \       \  
        2    6       9
 */
Java
/*package whatever //do not write package name here */

import java.io.*;
import java.util.LinkedList;
import java.util.Queue;

// Structure of the Binary Tree
class TreeNode {
    int info;
    TreeNode left, right;

    public TreeNode(int value) {
        info = value;
        left = right = null;
    }
}

public class LevelOrderTraversal {
    // Function to create the Binary Tree with predefined values
    public static TreeNode create() {
        // Hardcoded values for the binary tree
        TreeNode root = new TreeNode(2);
        root.left = new TreeNode(7);
        root.right = new TreeNode(5);
        root.left.left = new TreeNode(2);
        root.left.right = new TreeNode(6);
        root.right.right = new TreeNode(9);

        return root;
    }

    // Function to perform the level-order traversal
    public static void levelOrder(TreeNode root) {
        // If the root is null
        if (root == null)
            return;

        // Use a queue for traversal
        Queue<TreeNode> queue = new LinkedList<>();

        // Print the root's value and push it into the queue
        System.out.print(root.info + " ");
        queue.add(root);

        // Iterate until the queue is non-empty
        while (!queue.isEmpty()) {
            // Get the front node
            root = queue.poll();

            // If the root has a left child
            if (root.left != null) {
                System.out.print(root.left.info + " ");
                queue.add(root.left);
            }

            // If the root has a right child
            if (root.right != null) {
                System.out.print(root.right.info + " ");
                queue.add(root.right);
            }
        }
        System.out.println();
    }

    // Driver Code
    public static void main(String[] args) {
        // Function Call
        TreeNode root = create();

        // Perform Level-Order Traversal
        levelOrder(root);
    }
}

class GFG {
    public static void main (String[] args) {
        System.out.println("GFG!");
    }
}
// this code is contributed bu utkarsh
Python3
from collections import deque

# Structure of the Binary Tree
class TreeNode:
    def __init__(self, value):
        self.info = value
        self.left = None
        self.right = None

# Function to create the Binary Tree with predefined values
def create():
    # Hardcoded values for the binary tree
    root = TreeNode(2)
    root.left = TreeNode(7)
    root.right = TreeNode(5)
    root.left.left = TreeNode(2)
    root.left.right = TreeNode(6)
    root.right.right = TreeNode(9)

    return root

# Function to perform the level-order traversal
def level_order(root):
    # If the root is null
    if root is None:
        return

    # Use a queue for traversal
    queue = deque()

    # Print the root's value and push it into the queue
    print(root.info, end=" ")
    queue.append(root)

    # Iterate until the queue is non-empty
    while queue:
        # Get the front node
        root = queue.popleft()

        # If the root has a left child
        if root.left:
            print(root.left.info, end=" ")
            queue.append(root.left)

        # If the root has a right child
        if root.right:
            print(root.right.info, end=" ")
            queue.append(root.right)

    print()

# Driver Code
if __name__ == "__main__":
    # Function Call
    root = create()

    # Perform Level-Order Traversal
    level_order(root)
#this code is contributed by Utkarsh
C#
using System;
using System.Collections.Generic;

// Structure of the Binary Tree
public class TreeNode
{
    public int info;
    public TreeNode left, right;

    // Constructor to initialize TreeNode
    public TreeNode(int value)
    {
        info = value;
        left = right = null;
    }
}

public class LevelOrderTraversal
{
    // Function to create the Binary Tree with predefined values
    public static TreeNode Create()
    {
        // Hardcoded values for the binary tree
        TreeNode root = new TreeNode(2);
        root.left = new TreeNode(7);
        root.right = new TreeNode(5);
        root.left.left = new TreeNode(2);
        root.left.right = new TreeNode(6);
        root.right.right = new TreeNode(9);

        return root;
    }

    // Function to perform the level-order traversal
    public static void LevelOrder(TreeNode root)
    {
        // If the root is null
        if (root == null)
            return;

        // Use a queue for traversal
        Queue<TreeNode> queue = new Queue<TreeNode>();

        // Print the root's value and push it into the queue
        Console.Write(root.info + " ");
        queue.Enqueue(root);

        // Iterate until the queue is non-empty
        while (queue.Count > 0)
        {
            // Get the front node
            root = queue.Dequeue();

            // If the root has a left child
            if (root.left != null)
            {
                Console.Write(root.left.info + " ");
                queue.Enqueue(root.left);
            }

            // If the root has a right child
            if (root.right != null)
            {
                Console.Write(root.right.info + " ");
                queue.Enqueue(root.right);
            }
        }
        Console.WriteLine();
    }

    // Driver Code
    public static void Main(string[] args)
    {
        // Function Call
        TreeNode root = Create();

        // Perform Level-Order Traversal
        LevelOrder(root);
    }
}
//This code is contributed by Monu.
Javascript
// Structure of the Binary Tree
class TreeNode {
    constructor(value) {
        this.info = value;
        this.left = this.right = null;
    }
}

// Function to create the Binary Tree with predefined values
function create() {
    // Hardcoded values for the binary tree
    const root = new TreeNode(2);
    root.left = new TreeNode(7);
    root.right = new TreeNode(5);
    root.left.left = new TreeNode(2);
    root.left.right = new TreeNode(6);
    root.right.right = new TreeNode(9);

    return root;
}

// Function to perform the level-order traversal
function levelOrder(root) {
    // If the root is null
    if (root === null)
        return;

    // Use a queue for traversal
    const queue = [];

    // Print the root's value and push it into the queue
    process.stdout.write(root.info + " ");
    queue.push(root);

    // Iterate until the queue is non-empty
    while (queue.length > 0) {
        // Get the front node
        root = queue.shift();

        // If the root has a left child
        if (root.left !== null) {
            process.stdout.write(root.left.info + " ");
            queue.push(root.left);
        }

        // If the root has a right child
        if (root.right !== null) {
            process.stdout.write(root.right.info + " ");
            queue.push(root.right);
        }
    }
    process.stdout.write("\n");
}

// Driver Code
function main() {
    // Function Call
    const root = create();

    // Perform Level-Order Traversal
    levelOrder(root);
}

main();

// Additional code for GFG class
class GFG {
    static main() {
        console.log("GFG!");
    }
}

GFG.main();

Output:

level-order traversal

Time Complexity: O(N)
Auxiliary Space: O(N)

The maximum element of the Binary Tree:

 The element which is largest among all the elements of the binary tree is called the maximum element. Below is the program to illustrate the same:

C++
// C++ program for the above approach
#include "bits/stdc++.h"
using namespace std;

// Structure of the Binary Tree
struct treenode {
    int info;
    struct treenode *left, *right;
};

// Function to create the Binary Tree
struct treenode* create()
{
    int data;
    struct treenode* tree;

    // Dynamically allocating memory
    // for the tree-node
    tree = new treenode;

    cout << "\nEnter data to be inserted "
         << "or type -1 for no insertion : ";

    // Input from the user
    cin >> data;

    // Termination Condition
    if (data == -1)
        return 0;

    // Assign value from user into tree
    tree->info = data;

    // Recursively Call to create the
    // left and the right sub tree
    cout << "Enter left child of : " << data;
    tree->left = create();

    cout << "Enter right child of : " << data;
    tree->right = create();

    // Return the created Tree
    return tree;
};

// Function to find the maximum element
// in the given Binary Tree
int FindMax(struct treenode* root)
{
    // If the tree is empty
    if (root == NULL)
        return 0;

    queue<treenode*> q;
    int max;
    struct treenode* temp;

    max = root->info;

    // Push the root in the queue
    q.push(root);

    // Iterate until queue is non-empty
    while (!q.empty()) {

        // Get the front node of
        // the tree
        root = q.front();
        temp = root;
        q.pop();

        // Update the maximum value
        // of the Tree
        if (max < temp->info)
            max = temp->info;

        if (root->left) {
            q.push(root->left);
        }
        if (root->right) {
            q.push(root->right);
        }
    }

    // Return the maximum value
    return max;
}

// Driver Code
int main()
{
    // Root Node
    struct treenode* root = NULL;

    // Function Call
    root = create();

    // Perform Inorder Traversal
    FindMax(root);

    return 0;
}

/* Will be creating tree:
                2  
           /     \  
          7       5  
         /  \       \  
        2    6       9
 */
Java
import java.util.LinkedList;
import java.util.Queue;
import java.util.Scanner;

// Structure of the Binary Tree
class treenode {
    int info;
    treenode left, right;

    // Constructor
    public treenode(int data) {
        this.info = data;
        this.left = this.right = null;
    }
}

public class MaxElementInBinaryTree {
    // Function to create the Binary Tree
    static treenode create() {
        Scanner sc = new Scanner(System.in);
        int data;

        System.out.print("\nEnter data to be inserted " +
                "or type -1 for no insertion : ");
        data = sc.nextInt();

        // Termination Condition
        if (data == -1)
            return null;

        // Create a new tree node
        treenode tree = new treenode(data);

        // Recursively Call to create the
        // left and the right sub tree
        System.out.print("Enter left child of : " + data);
        tree.left = create();

        System.out.print("Enter right child of : " + data);
        tree.right = create();

        // Return the created Tree
        return tree;
    }

    // Function to find the maximum element
    // in the given Binary Tree
    static int FindMax(treenode root) {
        // If the tree is empty
        if (root == null)
            return 0;

        Queue<treenode> q = new LinkedList<>();
        int max;
        treenode temp;

        max = root.info;

        // Push the root in the queue
        q.add(root);

        // Iterate until the queue is non-empty
        while (!q.isEmpty()) {
            // Get the front node of the tree
            root = q.poll();
            temp = root;

            // Update the maximum value of the Tree
            if (max < temp.info)
                max = temp.info;

            if (root.left != null) {
                q.add(root.left);
            }
            if (root.right != null) {
                q.add(root.right);
            }
        }

        // Return the maximum value
        return max;
    }

    // Driver Code
    public static void main(String[] args) {
        // Root Node
        treenode root = null;

        // Function Call
        root = create();

        // Perform Inorder Traversal
        int result = FindMax(root);
        System.out.println("Maximum element in the Binary Tree: " + result);
    }
}
/* Will be creating tree:
                2  
           /     \  
          7       5  
         /  \       \  
        2    6       9
 */
Python
from queue import Queue

# Structure of the Binary Tree
class TreeNode:
    def __init__(self, value):
        self.info = value
        self.left = None
        self.right = None

# Function to create the Binary Tree
def create():
    print("\nEnter data to be inserted or type -1 for no insertion : ", end="")
    data = int(input())

    # Termination Condition
    if data == -1:
        return None

    # Dynamically allocate memory
    # for the tree-node
    tree = TreeNode(data)

    # Recursively Call to create the
    # left and the right sub tree
    print("Enter left child of", data, end=": ")
    tree.left = create()

    print("Enter right child of", data, end=": ")
    tree.right = create()

    # Return the created Tree
    return tree

# Function to find the maximum element
# in the given Binary Tree
def find_max(root):
    # If the tree is empty
    if root is None:
        return float('-inf')

    q = Queue()
    max_value = float('-inf')

    # Push the root in the queue
    q.put(root)

    # Iterate until queue is non-empty
    while not q.empty():
        # Get the front node of the tree
        root = q.get()

        # Update the maximum value of the Tree
        max_value = max(max_value, root.info)

        if root.left:
            q.put(root.left)
        if root.right:
            q.put(root.right)

    # Return the maximum value
    return max_value

# Driver Code
if __name__ == "__main__":
    # Root Node
    root = None

    # Function Call
    root = create()

    # Perform Inorder Traversal
    max_element = find_max(root)
    print("Maximum element in the tree:", max_element)
C#
using System;
using System.Collections.Generic;

// Structure of the Binary Tree
public class TreeNode {
    public int info;
    public TreeNode left, right;

    public TreeNode(int value) {
        info = value;
        left = null;
        right = null;
    }
}

public class BinaryTree {
    // Function to create the Binary Tree
    public static TreeNode Create() {
        int data;
        TreeNode tree;

        // Dynamically allocating memory
        // for the tree-node
        tree = new TreeNode(0);

        Console.Write("\nEnter data to be inserted or type -1 for no insertion : ");

        string input = Console.ReadLine();
        if (input == null)
            return null;

        // Input from the user
        data = int.Parse(input);

        // Termination Condition
        if (data == -1)
            return null;

        // Assign value from user into tree
        tree.info = data;

        // Recursively Call to create the
        // left and the right sub tree
        Console.Write("Enter left child of : " + data);
        tree.left = Create();

        Console.Write("Enter right child of : " + data);
        tree.right = Create();

        // Return the created Tree
        return tree;
    }

    // Function to find the maximum element
    // in the given Binary Tree
    public static int FindMax(TreeNode root) {
        // If the tree is empty
        if (root == null)
            return 0;

        Queue<TreeNode> q = new Queue<TreeNode>();
        int max;
        TreeNode temp;

        max = root.info;

        // Push the root in the queue
        q.Enqueue(root);

        // Iterate until queue is non-empty
        while (q.Count != 0) {
            // Get the front node of
            // the tree
            root = q.Dequeue();
            temp = root;

            // Update the maximum value
            // of the Tree
            if (max < temp.info)
                max = temp.info;

            if (root.left != null) {
                q.Enqueue(root.left);
            }
            if (root.right != null) {
                q.Enqueue(root.right);
            }
        }

        // Return the maximum value
        return max;
    }

    // Driver Code
    public static void Main(string[] args) {
        // Root Node
        TreeNode root = null;

        // Function Call
        root = Create();

        // Perform Inorder Traversal
        int max = FindMax(root);
        Console.WriteLine("Maximum element in the tree: " + max);
    }
}
Javascript
const prompt = require('prompt-sync')();

// Structure of the Binary Tree
class TreeNode {
    constructor(value) {
        this.info = value;
        this.left = null;
        this.right = null;
    }
}

// Function to create the Binary Tree
function create() {
    let data;
    let tree = new TreeNode(0); // Dynamically allocating memory for the tree-node

    console.log("\nEnter data to be inserted or type -1 for no insertion : ");
    let input = prompt();
    if (input === null)
        return null;

    // Input from the user
    data = parseInt(input);

    // Termination Condition
    if (data === -1)
        return null;

    // Assign value from user into tree
    tree.info = data;

    // Recursively Call to create the left and the right sub tree
    console.log("Enter left child of : " + data);
    tree.left = create();

    console.log("Enter right child of : " + data);
    tree.right = create();

    // Return the created Tree
    return tree;
}

// Function to find the maximum element in the given Binary Tree
function findMax(root) {
    // If the tree is empty
    if (root === null)
        return 0;

    const queue = [];
    let max;
    let temp;

    max = root.info;

    // Push the root in the queue
    queue.push(root);

    // Iterate until queue is non-empty
    while (queue.length !== 0) {
        // Get the front node of the tree
        root = queue.shift();
        temp = root;

        // Update the maximum value of the Tree
        if (max < temp.info)
            max = temp.info;

        if (root.left !== null) {
            queue.push(root.left);
        }
        if (root.right !== null) {
            queue.push(root.right);
        }
    }

    // Return the maximum value
    return max;
}

// Driver Code
function main() {
    // Root Node
    let root = null;

    // Function Call
    root = create();

    // Perform Inorder Traversal
    let max = findMax(root);
    console.log("Maximum element in the tree: " + max);
}

main();

Output:

Maximum element

Time Complexity: O(N)
Auxiliary Space: O(N)

Search for an element:

The approach to search for any particular element in the tree node is to perform any tree traversal on the given tree and check if there exists any node with the given searched value or not. If found to be true, then print “Element is Found”. Otherwise, print “Element  Not  Found”

Below is the program to illustrate the same:

C++
// C++ program for the above approach
#include "bits/stdc++.h"
using namespace std;

// Structure of the Binary Tree
struct treenode {
    int info;
    struct treenode *left, *right;
};

// Function to create the Binary Tree
struct treenode* create()
{
    int data;
    struct treenode* tree;

    // Dynamically allocating memory
    // for the tree-node
    tree = new treenode;

    cout << "\nEnter data to be inserted "
         << "or type -1 for no insertion : ";

    // Input from the user
    cin >> data;

    // Termination Condition
    if (data == -1)
        return 0;

    // Assign value from user into tree
    tree->info = data;

    // Recursively Call to create the
    // left and the right sub tree
    cout << "Enter left child of : " << data;
    tree->left = create();

    cout << "Enter right child of : " << data;
    tree->right = create();

    // Return the created Tree
    return tree;
};

// Function to search an element in the
// given Binary Tree
int FindElement(struct treenode* root,
                int data)
{
    // If the root is NULL
    if (root == NULL)
        return 0;

    queue<treenode*> q;
    struct treenode* temp;
    if (!root)
        return 0;

    else {
        // Push the root
        q.push(root);

        // Perform the level-order traversal
        while (!q.empty()) {
            // Get the root
            root = q.front();
            temp = root;
            q.pop();

            // If the node with value data
            // exists then return 1
            if (data == temp->info)
                return 1;

            // Recursively push the left and
            // the right child of the node
            if (root->left) {
                q.push(root->left);
            }
            if (root->right) {
                q.push(root->right);
            }
        }

        // Otherwise, not found
        return 0;
    }
}

// Driver Code
int main()
{
    int data;

    // Root of the tree
    struct treenode* root = NULL;

    // Create the Tree
    root = create();

    cout << "\nEnter element to searched : ";
    cin >> data;

    // Function Call
    if (FindElement(root, data) == 1)
        cout << "\nElement is found";
    else
        cout << "Element is not found";
    return 0;
}

/* Will be creating tree:
                2
           /     \
          7       5
         /  \       \
        2    6       9
 */
Java
// Java program for the above approach
import java.util.*;

// Structure of the Binary Tree
class TreeNode {
    int info;
    TreeNode left, right;

    // Constructor
    TreeNode(int data) {
        info = data;
        left = right = null;
    }
}

public class Main {
    // Function to create the Binary Tree
    public static TreeNode create(Scanner sc) {
        int data;

        // Dynamically allocating memory
        // for the tree-node
        TreeNode tree;

        System.out.print("\nEnter data to be inserted "
                + "or type -1 for no insertion : ");

        // Input from the user
        data = sc.nextInt();

        // Termination Condition
        if (data == -1)
            return null;

        // Assign value from user into tree
        tree = new TreeNode(data);

        // Recursively Call to create the
        // left and the right sub tree
        System.out.print("Enter left child of : " + data);
        tree.left = create(sc);

        System.out.print("Enter right child of : " + data);
        tree.right = create(sc);

        // Return the created Tree
        return tree;
    }

    // Function to search an element in the
    // given Binary Tree
    public static int findElement(TreeNode root, int data) {
        // If the root is NULL
        if (root == null)
            return 0;

        Queue<TreeNode> q = new LinkedList<>();
        TreeNode temp;

        // Push the root
        q.add(root);

        // Perform the level-order traversal
        while (!q.isEmpty()) {
            // Get the root
            root = q.poll();
            temp = root;

            // If the node with value data
            // exists then return 1
            if (data == temp.info)
                return 1;

            // Recursively push the left and
            // the right child of the node
            if (root.left != null) {
                q.add(root.left);
            }
            if (root.right != null) {
                q.add(root.right);
            }
        }

        // Otherwise, not found
        return 0;
    }

    // Driver Code
    public static void main(String[] args) {
        Scanner sc = new Scanner(System.in);
        int data;

        // Root of the tree
        TreeNode root = null;

        // Create the Tree
        root = create(sc);

        System.out.print("\nEnter element to searched : ");
        data = sc.nextInt();

        // Function Call
        if (findElement(root, data) == 1)
            System.out.println("\nElement is found");
        else
            System.out.println("Element is not found");
        
        sc.close(); // Closing the scanner
    }
}
//this code is contrbiuted  by Utkarsh.
Python3
# Function to create a new tree node
class TreeNode:
    def __init__(self, val=0, left=None, right=None):
        self.val = val
        self.left = left
        self.right = right

# Function to create a binary tree


def create_tree():
    data = int(input("Enter data to be inserted or type -1 for no insertion: "))
    if data == -1:
        return None

    # Create a new tree node
    node = TreeNode(data)

    # Recursively create the left and right subtrees
    node.left = create_tree()
    node.right = create_tree()

    return node

# Function to search for an element in the binary tree


def find_element(root, data):
    if root is None:
        return False

    # Create a queue for level-order traversal
    queue = []
    queue.append(root)

    while queue:
        # Dequeue the current node
        node = queue.pop(0)

        # If the node's value matches the target data, return True
        if node.val == data:
            return True

        # Enqueue the left and right children of the node
        if node.left:
            queue.append(node.left)
        if node.right:
            queue.append(node.right)

    # If the element is not found, return False
    return False


# Driver code
if __name__ == "__main__":
    # Create the binary tree
    root = create_tree()

    # Get the element to search for
    data = int(input("Enter element to search: "))

    # Search for the element and print the result
    if find_element(root, data):
        print("Element is found")
    else:
        print("Element is not found")
JavaScript
// Structure of the Binary Tree
class TreeNode {
    constructor(info) {
        this.info = info;
        this.left = null;
        this.right = null;
    }
}

// Function to create the Binary Tree
function createTree() {
    const readlineSync = require('readline-sync');
    const data = parseInt(readlineSync.question("\nEnter data to be inserted or type -1 for no insertion: "));
    
    // Termination Condition
    if (data === -1)
        return null;

    // Create new tree node with given data
    const tree = new TreeNode(data);

    // Recursively Call to create the
    // left and the right sub tree
    console.log(`Enter left child of ${data}:`);
    tree.left = createTree();

    console.log(`Enter right child of ${data}:`);
    tree.right = createTree();

    // Return the created Tree
    return tree;
};

// Function to search an element in the given Binary Tree
function findElement(root, data) {
    // If the root is NULL
    if (!root)
        return false;

    const queue = [];
    let temp;

    // Push the root
    queue.push(root);

    // Perform the level-order traversal
    while (queue.length !== 0) {
        // Get the root
        root = queue.shift();
        temp = root;

        // If the node with value data exists then return true
        if (data === temp.info)
            return true;

        // Recursively push the left and the right child of the node
        if (root.left)
            queue.push(root.left);

        if (root.right)
            queue.push(root.right);
    }

    // Otherwise, not found
    return false;
}

// Driver Code
function main() {
    const readlineSync = require('readline-sync');

    // Root of the tree
    let root = null;

    // Create the Tree
    root = createTree();

    const data = parseInt(readlineSync.question("\nEnter element to be searched: "));

    // Function Call
    if (findElement(root, data))
        console.log("\nElement is found");
    else
        console.log("Element is not found");
}

// Call the main function
main();

Output:

Search element

Time Complexity: O(log N)
Auxiliary Space: O(N)

Reverse Level Order Traversal:

Below is the program to illustrate the same:

C++
// C++ program for the above approach
#include "bits/stdc++.h"
using namespace std;

// Structure of the Binary Tree
struct treenode {
    int info;
    struct treenode *left, *right;
};

// Function to create the Binary Tree
struct treenode* create()
{
    int data;
    struct treenode* tree;

    // Dynamically allocating memory
    // for the tree-node
    tree = new treenode;

    cout << "\nEnter data to be inserted "
         << "or type -1 for no insertion : ";

    // Input from the user
    cin >> data;

    // Termination Condition
    if (data == -1)
        return 0;

    // Assign value from user into tree
    tree->info = data;

    // Recursively Call to create the
    // left and the right sub tree
    cout << "Enter left child of : " << data;
    tree->left = create();

    cout << "Enter right child of : " << data;
    tree->right = create();

    // Return the created Tree
    return tree;
};

// Function to print the reverse level
// order traversal of the given tree
void reversetree(struct treenode* root)
{
    // If the root is NULL
    if (root == NULL)
        return;

    queue<treenode*> q;
    stack<int> s;
    struct treenode* temp;
    q.push(root);

    // Until queue is empty
    while (!q.empty()) {
        // Get the front node
        temp = q.front();
        q.pop();

        // Push every countered node
        // data into stack
        s.push(temp->info);

        // Check for the left subtree
        if (temp->left)
            q.push(temp->left);

        // Check for the right subtree
        if (temp->right)
            q.push(temp->right);
    }

    // While S is non-empty, print
    // all the nodes
    while (!s.empty()) {
        cout << s.top() << " ";
        s.pop();
    }
}

// Driver Code
int main()
{
    // Create root node
    struct treenode* root = NULL;

    // Create a tree
    root = create();

    cout << "\nReversed tree is :  ";
    reversetree(root);
    return 0;
}
/* Will be creating tree:
                2
           /     \
          7       5
         /  \       \
        2    6       9
*/

Output:

Print tree in reverse order

Time Complexity: O(N)
Auxiliary Space: O(N)

Height of the tree:

The height of the binary tree is the longest path from the root node to any leaf node in the tree. Below is the program to illustrate the same:

C++
// C++ program for the above approach
#include "bits/stdc++.h"
using namespace std;

// Structure of the Binary Tree
struct treenode {
    int info;
    struct treenode *left, *right;
};

// Function to create the Binary Tree
struct treenode* create()
{
    int data;
    struct treenode* tree;

    // Dynamically allocating memory
    // for the tree-node
    tree = new treenode;

    cout << "\nEnter data to be inserted "
         << "or type -1 for no insertion : ";

    // Input from the user
    cin >> data;

    // Termination Condition
    if (data == -1)
        return 0;

    // Assign value from user into
    // the tree
    tree->info = data;

    // Recursively Call to create the
    // left and the right sub tree
    cout << "Enter left child of : "
         << data;
    tree->left = create();

    cout << "Enter right child of : "
         << data;
    tree->right = create();

    // Return the created Tree
    return tree;
};

// Function to find the height of
// the given Binary tree
int height(struct treenode* root)
{
    int x, y;

    // If root is NOT NULL
    if (root != NULL) {
        // x will contain the height
        // of left subtree
        x = height(root->left);

        // y will contain the height
        // of right subtree
        y = height(root->right);

        if (x > y)

            // Leaf node has one height
            // so x or y + 1
            return x + 1;
        else
            return y + 1;
    }
    return 0;
}

// Driver Code
int main()
{
    // Root Node
    struct treenode* root = NULL;

    // Create the tree
    root = create();

    cout << "\nHeight of the tree is :  "
         << height(root);

    return 0;
}
/* Will be creating tree:
                2
           /     \
          7       5
         /  \       \
        2    6       9
 */

Output:

Find height of the tree

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

The deepest node of the tree

The node which is present at the maximum or the last level is called the deepest node. Below is the program to implement the above approach:

C++
// C++ program for the above approach
#include "bits/stdc++.h"
using namespace std;

// Structure of the Binary Tree
struct treenode {
    int info;
    struct treenode *left, *right;
};

// Function to create the Binary Tree
struct treenode* create()
{
    int data;
    struct treenode* tree;

    // Dynamically allocating memory
    // for the tree-node
    tree = new treenode;

    cout << "\nEnter data to be inserted "
         << "or type -1 for no insertion : ";

    // Input from the user
    cin >> data;

    // Termination Condition
    if (data == -1)
        return 0;

    // Assign value from user into tree
    tree->info = data;

    // Recursively Call to create the
    // left and the right sub tree
    cout << "Enter left child of : " << data;
    tree->left = create();

    cout << "Enter right child of : " << data;
    tree->right = create();

    // Return the created Tree
    return tree;
};

// Function to find the deepest node
// of the given Binary Tree
int deepest(struct treenode* root)
{
    // If the root is NULL
    if (root == NULL)
        return 0;

    queue<treenode*> q;

    q.push(root);

    // While queue is non-empty
    while (!q.empty()) {
        // Get the front node of queue
        root = q.front();
        q.pop();

        // Check for the left and
        // the right subtree
        if (root->left)
            q.push(root->left);
        if (root->right)
            q.push(root->right);
    }

    // Return the value for the
    // deepest node
    return (root->info);
}

// Driver Code
int main()
{
    // Root Node
    struct treenode* root = NULL;

    // Create the tree
    root = create();

    cout << "\nDeepest node of the tree is :  " << deepest(root);

    return 0;
}

/* Will be creating tree:
                2
           /     \
          7       5
         /  \       \
        2    6       9
 */

Output:

Find the deepest node

Time Complexity: O(N)
Auxiliary Space: O(N)

Left view of the tree:

Below is the program to implement the same:

C++
// C++ program for the above approach
#include "bits/stdc++.h"
using namespace std;

// Structure of the Binary Tree
struct treenode {
    int info;
    struct treenode *left, *right;
};

// Function to create the Binary Tree
struct treenode* create()
{
    int data;
    struct treenode* tree;

    // Dynamically allocating memory
    // for the tree-node
    tree = new treenode;

    cout << "\nEnter data to be inserted "
         << "or type -1 for no insertion : ";

    // Input from the user
    cin >> data;

    // Termination Condition
    if (data == -1)
        return 0;

    // Assign value from user into tree
    tree->info = data;

    // Recursively Call to create the
    // left and the right sub tree
    cout << "Enter left child of : " << data;
    tree->left = create();

    cout << "Enter right child of : " << data;
    tree->right = create();

    // Return the created Tree
    return tree;
};

// Stores the maximum left size
int maxlevelleft = 0;

// Function to print the left view of
// the tree
void leftview(struct treenode* root,
              int level)
{
    if (root == NULL)
        return;

    // If current level is at least
    // the maximum left level
    if (level >= maxlevelleft) {
        // Print the data
        cout << root->info << " ";
        maxlevelleft++;
    }

    // Left and Right Subtree
    // recursive calls
    leftview(root->left, level + 1);
    leftview(root->right, level + 1);
}

// Driver Code
int main()
{
    // Root Node
    struct treenode* root = NULL;

    // Create the tree
    root = create();

    cout << "\nLeft view of the tree is :  ";

    // Function Call
    leftview(root, 0);

    return 0;
}

/* Will be creating tree:
                2
           /     \
          7       5
         /  \       \
        2    6       9
 */

Output:

Left view of tree

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

Right view of the tree:

Below is the program to illustrate the same:

C++
// C++ program to demonstrate the
// above concepts
#include "bits/stdc++.h"
using namespace std;

// Structure of the Binary Tree
struct treenode {
    int info;
    struct treenode *left,
        *right;
};

// Function to create the Binary Tree
struct treenode* create()
{
    int data;
    struct treenode* tree;

    // Dynamically allocating memory
    // for the tree-node
    tree = new treenode;

    cout << "\nEnter data to be inserted "
         << "or type -1 for no insertion : ";

    // Input from the user
    cin >> data;

    // Termination Condition
    if (data == -1)
        return 0;

    // Assign value from user into tree
    tree->info = data;

    // Recursively Call to create the
    // left and the right sub tree
    cout << "Enter left child of : "
         << data;
    tree->left = create();

    cout << "Enter right child of : "
         << data;
    tree->right = create();

    // Return the created Tree
    return tree;
};

// Stores the maximum right level
int maxlevelright = 0;

// Function to print the right view of
// the given Binary tree
void rightview(struct treenode* root,
               int level)
{
    // If the root is NULL
    if (root == NULL)
        return;

    // If the current level is greater
    // than the maximum right level
    if (level >= maxlevelright) {
        // Print the data
        cout << root->info << " ";
        maxlevelright++;
    }

    // Recursively call for the right
    // and the left subtree
    rightview(root->right, level + 1);
    rightview(root->left, level + 1);
}

// Driver Code
int main()
{
    // Root Node
    struct treenode* root = NULL;

    // Create the tree
    root = create();

    cout << "\nRight view of the tree is :  ";

    rightview(root, 0);

    return 0;
}
/* Will be creating tree:
                2
           /     \
          7       5
         /  \       \
        2    6       9
*/

Output:

Right view of the tree

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

Top view of the tree:

Below is the program to illustrate the same:

C++
// C++ program to demonstrate the
// above concepts
#include "bits/stdc++.h"
using namespace std;

// Structure of the Binary Tree
struct treenode {
    int info;
    struct treenode *left,
        *right;
};

// Function to create the Binary Tree
struct treenode* create()
{
    int data;
    struct treenode* tree;

    // Dynamically allocating memory
    // for the tree-node
    tree = new treenode;

    cout << "\nEnter data to be inserted "
         << "or type -1 for no insertion : ";

    // Input from the user
    cin >> data;

    // Termination Condition
    if (data == -1)
        return 0;

    // Assign value from user into tree
    tree->info = data;

    // Recursively Call to create the
    // left and the right sub tree
    cout << "Enter left child of : "
         << data;
    tree->left = create();

    cout << "Enter right child of : "
         << data;
    tree->right = create();

    // Return the created Tree
    return tree;
};

// Initialize an ordered map
map<int, int> HashMap;

// Iterator for the map
map<int, int>::iterator it;

// Function to print the top view
// of the given Binary Tree
void topview(struct treenode* root,
             int level)
{
    // If the root is NULL
    if (root == NULL)
        return;

    // Get the level
    int i = HashMap.count(level);

    // Update the root information
    if (i == 0)
        HashMap[level] = root->info;

    // Left and Right recursive calls
    topview(root->left, level - 1);
    topview(root->right, level + 1);

    // Update the current level
    // with the root's value
    HashMap[level] = root->info;

    return;
}

// Driver Code
int main()
{
    // Root Node
    struct treenode* root = NULL;

    // Create a tree
    root = create();

    topview(root, 0);
    cout << "\nTop view of the tree is : ";

    for (it = HashMap.begin();
         it != HashMap.end(); it++) {
        cout << it->second << " ";
    }

    return 0;
}
/* Will be creating tree:
                2
           /     \
          7       5
         /  \       \
        2    6       9
*/

Output:

Top view of the tree

Time Complexity: O(N)
Auxiliary Space: O(N)

Bottom view of the tree:

Below is the program to illustrate the same:

C++
// C++ program to demonstrate the
// above concepts
#include "bits/stdc++.h"
using namespace std;

// Structure of the Binary Tree
struct treenode {
    int info;
    struct treenode *left,
        *right;
};

// Function to create the Binary Tree
struct treenode* create()
{
    int data;
    struct treenode* tree;

    // Dynamically allocating memory
    // for the tree-node
    tree = new treenode;

    cout << "\nEnter data to be inserted "
         << "or type -1 for no insertion : ";

    // Input from the user
    cin >> data;

    // Termination Condition
    if (data == -1)
        return 0;

    // Assign value from user into tree
    tree->info = data;

    // Recursively Call to create the
    // left and the right sub tree
    cout << "Enter left child of : "
         << data;
    tree->left = create();

    cout << "Enter right child of : "
         << data;
    tree->right = create();

    // Return the created Tree
    return tree;
};

// Initialize an ordered Map
map<int, pair<int, int> > HashMap;

// Iterator for the map
map<int, pair<int, int> >::iterator it;

// Function to print the bottom view
// of the given binary tree
void bottomview(struct treenode* root,
                int level, int height)
{
    // If root is NULL
    if (root == NULL)
        return;

    // If the height of the level is
    // greater than the current
    // stored height of the level
    if (height >= HashMap[level].second) {
        HashMap[level] = { root->info,
                           height };
    }

    // Left and right recursive calls
    bottomview(root->left, level - 1,
               height + 1);
    bottomview(root->right, level + 1,
               height + 1);

    return;
}

// Driver Code
int main()
{
    // Root Node
    struct treenode* root = NULL;

    // Create the tree
    root = create();

    bottomview(root, 0, 0);
    cout << "\nBottom view of the tree is : ";

    for (it = HashMap.begin();
         it != HashMap.end(); it++) {

        cout << it->second.first << " ";
    }

    return 0;
}

/* Will be creating tree:
                2
           /     \
          7       5
         /  \       \
        2    6       9
 */

Output:

Bottom view of the tree

Time Complexity: O(N)
Auxiliary Space: O(N)

The mirror image of the tree

Below is the program to illustrate the same:

C++
// C++ program to implement
// the above approach
#include <iostream>
using namespace std;

// structure of the binary tree
struct treenode {
    // data part
    int info;

    // left and right node
    struct treenode *left, *right;
};

// create function for binary
// tree creation
struct treenode* create()
{
    int data;

    // variable of the structure
    struct treenode* tree;

    // dynamically allocating
    // memory for tree-node
    tree = new treenode;

    cout << "\nEnter data to be inserted or type -1 for no insertion : ";

    // input from the user
    cin >> data;

    // condition for termination
    if (data == -1)
        return 0;

    // assigning value from user
    // into tree.
    tree->info = data;

    // recursively calling create function
    // for left and right sub tree
    cout << "Enter left child of : " << data;
    tree->left = create();

    cout << "Enter right child of : " << data;
    tree->right = create();

    // returning the created tree
    return tree;
};

/*
With the simple logic of recursion and 
swapping, we can create mirror tree.
We will swap the left-node and 
right-node of root node. We will use 
recursion and start swapping from the 
bottom of the tree.
*/

// function to form mirror image a tree
void mirrortree(struct treenode* root)
{
    if (root != NULL) {
        mirrortree(root->left);
        mirrortree(root->right);

        struct treenode* temp;

        temp = root->left;
        root->left = root->right;
        root->right = temp;
    }
    return;
}

// function for the inorder traversal
void inorder(struct treenode* root)
{
    if (root == NULL)
        return;

    inorder(root->left);
    cout << root->info << "  ";
    inorder(root->right);
}

// Driver code
int main()
{
    // creating variable of the
    // structure
    struct treenode* root = NULL;

    // calling create function to
    // create tree
    root = create();

    mirrortree(root);
    cout << "\nInorder of the mirror tree is = ";
    inorder(root);

    return 0;
}

/* Will be creating tree:
                2
           /     \
          7       5
         /  \       \
        2    6       9
 */
Java
import java.util.Scanner;

// structure of the binary tree
class TreeNode {
    // data part
    int info;

    // left and right node
    TreeNode left, right;

    TreeNode(int info) {
        this.info = info;
        left = right = null;
    }
}

public class Main {
    // create function for binary tree creation
    static TreeNode create() {
        Scanner scanner = new Scanner(System.in);
        int data;

        // variable of the structure
        TreeNode tree;

        // dynamically allocating memory for tree-node
        System.out.print("\nEnter data to be inserted or type -1 for no insertion: ");
        data = scanner.nextInt();

        // condition for termination
        if (data == -1)
            return null;

        // assigning value from the user into tree
        tree = new TreeNode(data);

        // recursively calling create function for left and right subtree
        System.out.print("Enter left child of " + data + ": ");
        tree.left = create();

        System.out.print("Enter right child of " + data + ": ");
        tree.right = create();

        // returning the created tree
        return tree;
    }

    /*
    With the simple logic of recursion and 
    swapping, we can create a mirror tree.
    We will swap the left-node and right-node of root node. 
    We will use recursion and start swapping from the bottom of the tree.
    */

    // function to form mirror image of a tree
    static void mirrorTree(TreeNode root) {
        if (root != null) {
            mirrorTree(root.left);
            mirrorTree(root.right);

            TreeNode temp = root.left;
            root.left = root.right;
            root.right = temp;
        }
    }

    // function for the inorder traversal
    static void inorder(TreeNode root) {
        if (root == null)
            return;

        inorder(root.left);
        System.out.print(root.info + " ");
        inorder(root.right);
    }

    // Driver code
    public static void main(String[] args) {
        // creating variable of the structure
        TreeNode root;

        // calling create function to create tree
        root = create();

        mirrorTree(root);
        System.out.print("\nInorder of the mirror tree is = ");
        inorder(root);
    }
}

Output:

Mirror tree

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

Serialize a tree:

Serialization of a tree is defined as the conversion of the given tree into a data-format that can be later restored and the structure of the tree must be maintained. Below is the program to implement the above approach:

C++
#include <iostream>
#include <vector>
using namespace std;

// Structure of the binary tree
struct treenode {
    int info;
    struct treenode *left, *right;
};

// Function to create a binary tree
struct treenode* create() {
    int data;
    struct treenode* tree = new treenode;

    cout << "\nEnter data to be inserted or type -1 for no insertion: ";
    cin >> data;

    if (data == -1)
        return nullptr;

    tree->info = data;

    cout << "Enter left child of " << data << ": ";
    tree->left = create();

    cout << "Enter right child of " << data << ": ";
    tree->right = create();

    return tree;
}

// Function to serialize the binary tree
void serialize(struct treenode* root, vector<int>& v) {
    if (root == nullptr) {
        v.push_back(-1);
        return;
    }

    v.push_back(root->info);
    serialize(root->left, v);
    serialize(root->right, v);
}

// Driver Code
int main() {
    struct treenode* root = nullptr;
    root = create();

    vector<int> v;
    serialize(root, v);

    cout << "\nSerialized form of the tree: ";
    for (int i = 0; i < v.size(); i++)
        cout << v[i] << " ";

    // Memory deallocation
    delete root;

    return 0;
}
Java
import java.util.*;

// structure of the binary tree
class TreeNode {
    // data part
    int info;

    // left and right node
    TreeNode left, right;

    // constructor
    TreeNode(int item)
    {
        info = item;
        left = right = null;
    }
}

class SerializeDeserializeBinaryTree {
    // create function for binary
    // tree creation
    public static TreeNode create()
    {
        int data;

        // variable of the structure
        TreeNode tree;

        // dynamically allocating
        // memory for tree-node
        tree = new TreeNode(0);

        Scanner sc = new Scanner(System.in);
        System.out.print(
            "\nEnter data to be inserted or type -1 for no insertion : ");

        // input from the user
        data = sc.nextInt();

        // condition for termination
        if (data == -1)
            return null;

        // assigning value from user
        // into tree.
        tree.info = data;

        // recursively calling create function
        // for left and right sub tree
        System.out.print("Enter left child of : " + data);
        tree.left = create();

        System.out.print("Enter right child of : " + data);
        tree.right = create();

        // returning the created tree
        return tree;
    }

    // Function to serialize the given
    // Binary Tree
    public static void serialize(TreeNode root,
                                 List<Integer> v)
    {
        // If the root is NULL, then
        // push -1 and return
        if (root == null) {
            v.add(-1);
            return;
        }

        // Otherwise, push the data part
        v.add(root.info);

        // Recursively Call for the left
        // and the right Subtree
        serialize(root.left, v);
        serialize(root.right, v);
    }

    // Driver Code
    public static void main(String args[])
    {
        // Root Node
        TreeNode root = null;

        // Create a tree
        root = create();

        List<Integer> v = new ArrayList<Integer>();

        serialize(root, v);
        System.out.print(
            "\nSerialize form of the tree is = ");

        for (int i = 0; i < v.size(); i++)
            System.out.print(v.get(i) + "  ");
    }
}

/* Will be creating tree:
2
/
7 5
/ \
2 6 9
*/
Python
# Structure of the Binary Tree
class TreeNode:
    def __init__(self, info):
        self.info = info
        self.left = None
        self.right = None

# Function to create the Binary Tree
def create(values):
    data = values.pop(0)

    # Termination Condition
    if data == -1:
        return None

    # Assign value from values list into tree
    tree = TreeNode(data)

    # Recursively Call to create the left and the right sub tree
    tree.left = create(values)
    tree.right = create(values)

    # Return the created Tree
    return tree

# Function to serialize the given Binary Tree
def serialize(root, result):
    # If the root is None, then push -1 and return
    if root is None:
        result.append(-1)
        return

    # Otherwise, push the data part
    result.append(root.info)

    # Recursively Call for the left and the right Subtree
    serialize(root.left, result)
    serialize(root.right, result)

# Driver Code
if __name__ == "__main__":
    # Provide the input data directly
    input_values = [2, 7, 2, -1, -1, 6, -1, -1, 5, -1, 9, -1, -1]

    # Root Node
    root = create(input_values[:])

    result = []

    serialize(root, result)
    print("\nSerialize form of the tree is =", result)
JavaScript
// structure of the binary tree
class TreeNode {
    // data part
    constructor(info) {
        this.info = info;
        this.left = null;
        this.right = null;
    }
}

class SerializeDeserializeBinaryTree {
    // create function for binary
    // tree creation
    static create(inputData) {
        let data = inputData.shift(); // Get the first value from input array

        // condition for termination
        if (data === -1)
            return null;

        // variable of the structure
        let tree = new TreeNode(data);

        // recursively calling create function
        // for left and right sub tree
        console.log("Enter left child of : " + data);
        tree.left = SerializeDeserializeBinaryTree.create(inputData);

        console.log("Enter right child of : " + data);
        tree.right = SerializeDeserializeBinaryTree.create(inputData);

        // returning the created tree
        return tree;
    }

    // Function to serialize the given
    // Binary Tree
    static serialize(root, v) {
        // If the root is NULL, then
        // push -1 and return
        if (root === null) {
            v.push(-1);
            return;
        }

        // Otherwise, push the data part
        v.push(root.info);

        // Recursively Call for the left
        // and the right Subtree
        SerializeDeserializeBinaryTree.serialize(root.left, v);
        SerializeDeserializeBinaryTree.serialize(root.right, v);
    }
}

// Driver Code
(function () {
    // Create a tree
    let inputData = [2, 7, 2, -1, -1, 6, -1, -1, 5, -1, 9, -1, -1];
    let root = SerializeDeserializeBinaryTree.create(inputData);

    let v = [];

    SerializeDeserializeBinaryTree.serialize(root, v);
    console.log("\nSerialize form of the tree is = " + v.join("  "));
})();

Output:

Serialize a tree

Time Complexity: O(N)
Auxiliary Space: O(N)

Complexity Analysis:

  1. Time Complexity: O(n).
  2. Auxiliary Space: O(1).


Like Article
Suggest improvement
Previous
Next
Share your thoughts in the comments

Similar Reads