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”.

Below are the various operations that can be performed on a 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++
#include <iostream>
using namespace std;
struct treenode {
int info;
struct treenode *left,
*right;
};
struct treenode* create()
{
int data;
struct treenode* tree;
tree = new treenode;
cout << "\nEnter data to be inserted "
<< "or type -1 for no insertion : ";
cin >> data;
if (data == -1)
return 0;
tree->info = data;
cout << "Enter left child of : "
<< data;
tree->left = create();
cout << "Enter right child of : "
<< data;
tree->right = create();
return tree;
};
void inorder(struct treenode* root)
{
if (root == NULL)
return;
inorder(root->left);
cout << root->info << " ";
inorder(root->right);
}
int main()
{
struct treenode* root = NULL;
root = create();
inorder(root);
return 0;
}
|
Java
import java.util.Scanner;
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);
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;
}
static void inorder(TreeNode root) {
if (root == null) {
return;
}
inorder(root.left);
System.out.print(root.info + " ");
inorder(root.right);
}
public static void main(String[] args) {
TreeNode root = null;
root = create();
inorder(root);
}
}
|
Python3
class TreeNode:
def __init__(self, data):
self.info = data
self.left = None
self.right = None
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
def inorder(root):
if root == None:
return
inorder(root.left)
print(root.info, end=" ")
inorder(root.right)
if __name__ == '__main__':
root = None
root = create()
inorder(root)
|
C#
using System;
public class treenode {
public int info;
public treenode left, right;
public treenode()
{
info = 0;
left = null;
right = null;
}
}
public class GFG {
public static treenode create()
{
int data;
treenode tree = new treenode();
Console.WriteLine(
"\nEnter data to be inserted "
+ "or type -1 for no insertion : ");
data = Convert.ToInt32(Console.ReadLine());
if (data == -1)
return null;
tree.info = data;
Console.WriteLine("Enter left child of : " + data);
tree.left = create();
Console.WriteLine("Enter right child of : " + data);
tree.right = create();
return tree;
}
public static void inorder(treenode root)
{
if (root == null)
return;
inorder(root.left);
Console.Write(root.info + " ");
inorder(root.right);
}
public static void Main()
{
treenode root = null;
root = create();
inorder(root);
}
}
|
Javascript
class treenode {
constructor(){
this.info = 0;
this.left = null;
this.right = null;
}
}
function create()
{
let data;
let tree = new treenode();
data = prompt("\n Enter data to be inserted or type -1 for no insertion :");
if (data == -1)
return 0;
tree.info = data;
console.log("Enter left child of : " + data);
tree.left = create();
console.log("Enter right child of : " + data);
tree.right = create();
return tree;
}
function inorder(root)
{
if (root == null)
return;
inorder(root.left);
console.log(root.info);
inorder(root.right);
}
let root = null;
root = create();
inorder(root);
|
Output:

Time Complexity: O(N)
Auxiliary Space: O(1)
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++
#include "bits/stdc++.h"
using namespace std;
struct treenode {
int info;
struct treenode *left,
*right;
};
struct treenode* create()
{
int data;
struct treenode* tree;
tree = new treenode;
cout << "\nEnter data to be inserted "
<< "or type -1 for no insertion : ";
cin >> data;
if (data == -1)
return 0;
tree->info = data;
cout << "Enter left child of : "
<< data;
tree->left = create();
cout << "Enter right child of : "
<< data;
tree->right = create();
return tree;
};
void preorder(struct treenode* root)
{
if (root == NULL)
return;
stack<treenode*> s;
while ((root != NULL) || (!s.empty())) {
if (root != NULL) {
cout << root->info << " ";
s.push(root);
root = root->left;
}
else {
root = s.top();
s.pop();
root = root->right;
}
}
cout << endl;
}
int main()
{
struct treenode* root = NULL;
root = create();
preorder(root);
return 0;
}
|
Java
import java.io.*;
import java.util.Scanner;
import java.util.Stack;
class TreeNode {
int info;
TreeNode left;
TreeNode right;
TreeNode(int info) {
this.info = info;
left = null;
right = null;
}
}
class GFG {
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();
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;
}
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) {
TreeNode root = null;
root = create();
preorder(root);
}
}
|
Python3
class TreeNode:
def __init__(self, val=0, left=None, right=None):
self.val = val
self.left = left
self.right = right
def create():
data = int(input("\nEnter data to be inserted or type -1 for no insertion: "))
if data == -1:
return None
root = TreeNode(data)
print("Enter left child of:", data)
root.left = create()
print("Enter right child of:", data)
root.right = create()
return root
def preorder(root):
if not root:
return
stack = []
while root or stack:
if root:
print(root.val, end=" ")
stack.append(root)
root = root.left
else:
root = stack.pop()
root = root.right
print()
if __name__ == "__main__":
root = None
root = create()
preorder(root)
|
C#
using System;
using System.Collections.Generic;
class TreeNode
{
public int info;
public TreeNode left;
public TreeNode right;
public TreeNode(int info)
{
this.info = info;
left = null;
right = null;
}
}
class GFG
{
public static TreeNode Create()
{
Console.Write("Enter data to be inserted or type -1 for no insertion: ");
int data = Convert.ToInt32(Console.ReadLine());
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;
}
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)
{
TreeNode root = null;
root = Create();
Preorder(root);
}
}
|
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 : "
);
if (data == -1) return null;
let tree = new TreeNode(data);
tree.left = create();
tree.right = create();
return tree;
}
function preorder(root) {
if (root == null) return;
let s = [];
while (root != null || s.length > 0) {
if (root != null) {
console.log(root.info);
s.push(root);
root = root.left;
} else {
root = s.pop();
root = root.right;
}
}
}
let root = null;
root = create();
preorder(root);
|
Output:

Time Complexity: O(N)
Auxiliary Space: O(N)
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++
#include "bits/stdc++.h"
using namespace std;
struct treenode {
int info;
struct treenode *left,
*right;
};
struct treenode* create()
{
int data;
struct treenode* tree;
tree = new treenode;
cout << "\nEnter data to be inserted "
<< "or type -1 for no insertion : ";
cin >> data;
if (data == -1)
return 0;
tree->info = data;
cout << "Enter left child of : "
<< data;
tree->left = create();
cout << "Enter right child of : "
<< data;
tree->right = create();
return tree;
};
void inorder(struct treenode* root)
{
if (root == NULL)
return;
inorder(root->left);
cout << root->info << " ";
inorder(root->right);
}
int main()
{
struct treenode* root = NULL;
root = create();
inorder(root);
return 0;
}
|
Java
import java.util.Scanner;
class TreeNode {
int info;
TreeNode left;
TreeNode right;
}
public class BinaryTreeCreation {
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();
if (data == -1) {
return null;
}
tree.info = 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;
}
public static void inorder(TreeNode root) {
if (root == null) {
return;
}
inorder(root.left);
System.out.print(root.info + " ");
inorder(root.right);
}
public static void main(String[] args) {
TreeNode root = null;
root = create();
System.out.print("Inorder Traversal: ");
inorder(root);
}
}
|
Python3
class TreeNode:
def __init__(self, info):
self.info = info
self.left = None
self.right = None
def create():
data = int(input("Enter data to be inserted or type -1 for no insertion: "))
if data == -1:
return None
tree = TreeNode(data)
print("Enter left child of:", data)
tree.left = create()
print("Enter right child of:", data)
tree.right = create()
return tree
def inorder(root):
if root is None:
return
inorder(root.left)
print(root.info, end=" ")
inorder(root.right)
root = create()
inorder(root)
|
C#
using System;
class TreeNode
{
public int Info;
public TreeNode Left, Right;
public TreeNode(int data)
{
Info = data;
Left = Right = null;
}
}
class BinaryTree
{
static TreeNode CreateTree()
{
int data;
Console.Write("\nEnter data to be inserted " +
"or type -1 for no insertion: ");
if (!int.TryParse(Console.ReadLine(), out data) || data == -1)
{
return null;
}
TreeNode tree = new TreeNode(data);
Console.Write("Enter left child of " + data + ": ");
tree.Left = CreateTree();
Console.Write("Enter right child of " + data + ": ");
tree.Right = CreateTree();
return tree;
}
static void Inorder(TreeNode root)
{
if (root == null)
return;
Inorder(root.Left);
Console.Write(root.Info + " ");
Inorder(root.Right);
}
static void Main()
{
TreeNode root = null;
root = CreateTree();
Inorder(root);
}
}
|
Javascript
class TreeNode {
constructor(info) {
this.info = info;
this.left = null;
this.right = null;
}
}
function create() {
const tree = new TreeNode();
let data;
console.log("Enter data to be inserted or type -1 for no insertion : ");
data = parseInt(prompt());
if (data === -1)
return null;
tree.info = data;
console.log(`Enter left child of ${data}: `);
tree.left = create();
console.log(`Enter right child of ${data}: `);
tree.right = create();
return tree;
}
function inorder(root) {
if (root == null)
return;
inorder(root.left);
console.log(`${root.info} `);
inorder(root.right);
}
function main() {
let root = null;
root = create();
inorder(root);
}
main();
|
Output:

Time Complexity: O(N)
Auxiliary Space: O(N)
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++
#include "bits/stdc++.h"
using namespace std;
struct treenode {
int info;
struct treenode *left,
*right;
};
struct treenode* create()
{
int data;
struct treenode* tree;
tree = new treenode;
cout << "\nEnter data to be inserted "
<< "or type -1 for no insertion : ";
cin >> data;
if (data == -1)
return 0;
tree->info = data;
cout << "Enter left child of : "
<< data;
tree->left = create();
cout << "Enter right child of : "
<< data;
tree->right = create();
return tree;
};
void postorder(struct treenode* root)
{
return;
stack<treenode*> s3;
struct treenode* previous = NULL;
do {
while (root != NULL) {
s3.push(root);
root = root->left;
}
while (root == NULL && (!s3.empty())) {
root = s3.top();
if (root->right == NULL
|| root->right == previous) {
cout << root->info << " ";
s3.pop();
previous = root;
root = NULL;
}
else
root = root->right;
}
} while (!s3.empty());
cout << endl;
}
int main()
{
struct treenode* root = NULL;
root = create();
postorder(root);
return 0;
}
|
Java
import java.util.Stack;
import java.util.Scanner;
class TreeNode {
int info;
TreeNode left, right;
public TreeNode(int data) {
info = data;
left = right = null;
}
}
class PostOrderTraversal {
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();
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;
}
public static void postOrder(TreeNode root) {
if (root == null)
return;
Stack<TreeNode> stack = new Stack<>();
TreeNode previous = null;
do {
while (root != null) {
stack.push(root);
root = root.left;
}
while (root == null && !stack.isEmpty()) {
root = stack.pop();
if (root.right == null || root.right == previous) {
System.out.print(root.info + " ");
previous = root;
root = null;
} else {
root = root.right;
}
}
} while (!stack.isEmpty());
System.out.println();
}
public static void main(String[] args) {
TreeNode root;
root = create();
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()
if __name__ == "__main__":
root = None
root = create()
post_order(root)
|
C#
using System;
using System.Collections.Generic;
class TreeNode
{
public int Info;
public TreeNode Left, Right;
public TreeNode(int data)
{
Info = data;
Left = Right = null;
}
}
class PostOrderTraversal
{
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);
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;
}
catch (FormatException)
{
Console.WriteLine("Invalid input. Please enter a valid integer.");
return Create();
}
}
public static void PostOrder(TreeNode root)
{
if (root == null)
return;
Stack<TreeNode> stack = new Stack<TreeNode>();
TreeNode previous = null;
do
{
while (root != null)
{
stack.Push(root);
root = root.Left;
}
while (root == null && stack.Count > 0)
{
root = stack.Pop();
if (root.Right == null || root.Right == previous)
{
Console.Write(root.Info + " ");
previous = root;
root = null;
}
else
{
root = root.Right;
}
}
} while (stack.Count > 0);
Console.WriteLine();
}
public static void Main(string[] args)
{
TreeNode root;
root = Create();
PostOrder(root);
}
}
|
Javascript
class TreeNode {
constructor(data) {
this.info = data;
this.left = this.right = null;
}
}
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);
if (data === -1) {
rl.close();
resolve(null);
} else {
const tree = new TreeNode(data);
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 postOrder(root) {
if (root === null)
return;
const stack = [];
let previous = null;
do {
while (root !== null) {
stack.push(root);
root = root.left;
}
while (root === null && stack.length > 0) {
root = stack.pop();
if (root.right === null || root.right === previous) {
process.stdout.write(root.info + " ");
previous = root;
root = null;
} else {
root = root.right;
}
}
} while (stack.length > 0);
console.log();
}
async function main() {
const root = await create();
postOrder(root);
}
main();
|
Output:

Time Complexity: O(N)
Auxiliary Space: O(N)
In this traversal, the given tree is traversal level-wise. Below is the program to illustrate the same:
C++
using namespace std;
struct treenode {
int info;
struct treenode *left,
*right;
};
struct treenode* create()
{
int data;
struct treenode* tree;
tree = new treenode;
cout << "\nEnter data to be inserted "
<< "or type -1 for no insertion : ";
cin >> data;
if (data == -1)
return 0;
tree->info = data;
cout << "Enter left child of : "
<< data;
tree->left = create();
cout << "Enter right child of : "
<< data;
tree->right = create();
return tree;
};
void levelorder(struct treenode* root)
{
if (root == NULL)
return;
queue<treenode*> q;
cout << root->info << " ";
q.push(root);
while (!q.empty()) {
root = q.front();
q.pop();
if (root->left) {
cout << root->left->info
<< " ";
q.push(root->left);
}
if (root->right) {
cout << root->right->info
<< " ";
q.push(root->right);
}
}
cout << endl;
}
int main()
{
struct treenode* root = NULL;
root = create();
levelorder(root);
return 0;
}
|
Output:

Time Complexity: O(N)
Auxiliary Space: O(N)
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++
#include "bits/stdc++.h"
using namespace std;
struct treenode {
int info;
struct treenode *left, *right;
};
struct treenode* create()
{
int data;
struct treenode* tree;
tree = new treenode;
cout << "\nEnter data to be inserted "
<< "or type -1 for no insertion : ";
cin >> data;
if (data == -1)
return 0;
tree->info = data;
cout << "Enter left child of : " << data;
tree->left = create();
cout << "Enter right child of : " << data;
tree->right = create();
return tree;
};
int FindMax(struct treenode* root)
{
if (root == NULL)
return 0;
queue<treenode*> q;
int max;
struct treenode* temp;
max = root->info;
q.push(root);
while (!q.empty()) {
root = q.front();
temp = root;
q.pop();
if (max < temp->info)
max = temp->info;
if (root->left) {
q.push(root->left);
}
if (root->right) {
q.push(root->right);
}
}
return max;
}
int main()
{
struct treenode* root = NULL;
root = create();
FindMax(root);
return 0;
}
|
Output:

Time Complexity: O(N)
Auxiliary Space: O(N)
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++
#include "bits/stdc++.h"
using namespace std;
struct treenode {
int info;
struct treenode *left, *right;
};
struct treenode* create()
{
int data;
struct treenode* tree;
tree = new treenode;
cout << "\nEnter data to be inserted "
<< "or type -1 for no insertion : ";
cin >> data;
if (data == -1)
return 0;
tree->info = data;
cout << "Enter left child of : " << data;
tree->left = create();
cout << "Enter right child of : " << data;
tree->right = create();
return tree;
};
int FindElement(struct treenode* root,
int data)
{
if (root == NULL)
return 0;
queue<treenode*> q;
struct treenode* temp;
if (!root)
return 0;
else {
q.push(root);
while (!q.empty()) {
root = q.front();
temp = root;
q.pop();
if (data == temp->info)
return 1;
if (root->left) {
q.push(root->left);
}
if (root->right) {
q.push(root->right);
}
}
return 0;
}
}
int main()
{
int data;
struct treenode* root = NULL;
root = create();
cout << "\nEnter element to searched : ";
cin >> data;
if (FindElement(root, data) == 1)
cout << "\nElement is found";
else
cout << "Element is not found";
return 0;
}
|
Output:

Time Complexity: O(log N)
Auxiliary Space: O(N)
Reverse Level Order Traversal:
Below is the program to illustrate the same:
C++
#include "bits/stdc++.h"
using namespace std;
struct treenode {
int info;
struct treenode *left, *right;
};
struct treenode* create()
{
int data;
struct treenode* tree;
tree = new treenode;
cout << "\nEnter data to be inserted "
<< "or type -1 for no insertion : ";
cin >> data;
if (data == -1)
return 0;
tree->info = data;
cout << "Enter left child of : " << data;
tree->left = create();
cout << "Enter right child of : " << data;
tree->right = create();
return tree;
};
void reversetree(struct treenode* root)
{
if (root == NULL)
return;
queue<treenode*> q;
stack<int> s;
struct treenode* temp;
q.push(root);
while (!q.empty()) {
temp = q.front();
q.pop();
s.push(temp->info);
if (temp->left)
q.push(temp->left);
if (temp->right)
q.push(temp->right);
}
while (!s.empty()) {
cout << s.top() << " ";
s.pop();
}
}
int main()
{
struct treenode* root = NULL;
root = create();
cout << "\nReversed tree is : ";
reversetree(root);
return 0;
}
|
Output:

Time Complexity: O(N)
Auxiliary Space: O(N)
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++
#include "bits/stdc++.h"
using namespace std;
struct treenode {
int info;
struct treenode *left, *right;
};
struct treenode* create()
{
int data;
struct treenode* tree;
tree = new treenode;
cout << "\nEnter data to be inserted "
<< "or type -1 for no insertion : ";
cin >> data;
if (data == -1)
return 0;
tree->info = data;
cout << "Enter left child of : "
<< data;
tree->left = create();
cout << "Enter right child of : "
<< data;
tree->right = create();
return tree;
};
int height(struct treenode* root)
{
int x, y;
if (root != NULL) {
x = height(root->left);
y = height(root->right);
if (x > y)
return x + 1;
else
return y + 1;
}
return 0;
}
int main()
{
struct treenode* root = NULL;
root = create();
cout << "\nHeight of the tree is : "
<< height(root);
return 0;
}
|
Output:

Time Complexity: O(N)
Auxiliary Space: O(1)
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++
#include "bits/stdc++.h"
using namespace std;
struct treenode {
int info;
struct treenode *left, *right;
};
struct treenode* create()
{
int data;
struct treenode* tree;
tree = new treenode;
cout << "\nEnter data to be inserted "
<< "or type -1 for no insertion : ";
cin >> data;
if (data == -1)
return 0;
tree->info = data;
cout << "Enter left child of : " << data;
tree->left = create();
cout << "Enter right child of : " << data;
tree->right = create();
return tree;
};
int deepest(struct treenode* root)
{
if (root == NULL)
return 0;
queue<treenode*> q;
q.push(root);
while (!q.empty()) {
root = q.front();
q.pop();
if (root->left)
q.push(root->left);
if (root->right)
q.push(root->right);
}
return (root->info);
}
int main()
{
struct treenode* root = NULL;
root = create();
cout << "\nDeepest node of the tree is : " << deepest(root);
return 0;
}
|
Output:

Time Complexity: O(N)
Auxiliary Space: O(N)
Below is the program to implement the same:
C++
#include "bits/stdc++.h"
using namespace std;
struct treenode {
int info;
struct treenode *left, *right;
};
struct treenode* create()
{
int data;
struct treenode* tree;
tree = new treenode;
cout << "\nEnter data to be inserted "
<< "or type -1 for no insertion : ";
cin >> data;
if (data == -1)
return 0;
tree->info = data;
cout << "Enter left child of : " << data;
tree->left = create();
cout << "Enter right child of : " << data;
tree->right = create();
return tree;
};
int maxlevelleft = 0;
void leftview(struct treenode* root,
int level)
{
if (root == NULL)
return;
if (level >= maxlevelleft) {
cout << root->info << " ";
maxlevelleft++;
}
leftview(root->left, level + 1);
leftview(root->right, level + 1);
}
int main()
{
struct treenode* root = NULL;
root = create();
cout << "\nLeft view of the tree is : ";
leftview(root, 0);
return 0;
}
|
Output:

Time Complexity: O(N)
Auxiliary Space: O(1)
Below is the program to illustrate the same:
C++
#include "bits/stdc++.h"
using namespace std;
struct treenode {
int info;
struct treenode *left,
*right;
};
struct treenode* create()
{
int data;
struct treenode* tree;
tree = new treenode;
cout << "\nEnter data to be inserted "
<< "or type -1 for no insertion : ";
cin >> data;
if (data == -1)
return 0;
tree->info = data;
cout << "Enter left child of : "
<< data;
tree->left = create();
cout << "Enter right child of : "
<< data;
tree->right = create();
return tree;
};
int maxlevelright = 0;
void rightview(struct treenode* root,
int level)
{
if (root == NULL)
return;
if (level >= maxlevelright) {
cout << root->info << " ";
maxlevelright++;
}
rightview(root->right, level + 1);
rightview(root->left, level + 1);
}
int main()
{
struct treenode* root = NULL;
root = create();
cout << "\nRight view of the tree is : ";
rightview(root, 0);
return 0;
}
|
Output:

Time Complexity: O(N)
Auxiliary Space: O(1)
Below is the program to illustrate the same:
C++
#include "bits/stdc++.h"
using namespace std;
struct treenode {
int info;
struct treenode *left,
*right;
};
struct treenode* create()
{
int data;
struct treenode* tree;
tree = new treenode;
cout << "\nEnter data to be inserted "
<< "or type -1 for no insertion : ";
cin >> data;
if (data == -1)
return 0;
tree->info = data;
cout << "Enter left child of : "
<< data;
tree->left = create();
cout << "Enter right child of : "
<< data;
tree->right = create();
return tree;
};
map<int, int> HashMap;
map<int, int>::iterator it;
void topview(struct treenode* root,
int level)
{
if (root == NULL)
return;
int i = HashMap.count(level);
if (i == 0)
HashMap[level] = root->info;
topview(root->left, level - 1);
topview(root->right, level + 1);
HashMap[level] = root->info;
return;
}
int main()
{
struct treenode* root = NULL;
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;
}
|
Output:

Time Complexity: O(N)
Auxiliary Space: O(N)
Below is the program to illustrate the same:
C++
#include "bits/stdc++.h"
using namespace std;
struct treenode {
int info;
struct treenode *left,
*right;
};
struct treenode* create()
{
int data;
struct treenode* tree;
tree = new treenode;
cout << "\nEnter data to be inserted "
<< "or type -1 for no insertion : ";
cin >> data;
if (data == -1)
return 0;
tree->info = data;
cout << "Enter left child of : "
<< data;
tree->left = create();
cout << "Enter right child of : "
<< data;
tree->right = create();
return tree;
};
map<int, pair<int, int> > HashMap;
map<int, pair<int, int> >::iterator it;
void bottomview(struct treenode* root,
int level, int height)
{
if (root == NULL)
return;
if (height >= HashMap[level].second) {
HashMap[level] = { root->info,
height };
}
bottomview(root->left, level - 1,
height + 1);
bottomview(root->right, level + 1,
height + 1);
return;
}
int main()
{
struct treenode* root = NULL;
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;
}
|
Output:

Time Complexity: O(N)
Auxiliary Space: O(N)
Below is the program to illustrate the same:
C++
#include <iostream>
using namespace std;
struct treenode {
int info;
struct treenode *left, *right;
};
struct treenode* create()
{
int data;
struct treenode* tree;
tree = new treenode;
cout << "\nEnter data to be inserted or type -1 for no insertion : ";
cin >> data;
if (data == -1)
return 0;
tree->info = data;
cout << "Enter left child of : " << data;
tree->left = create();
cout << "Enter right child of : " << data;
tree->right = create();
return 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;
}
void inorder(struct treenode* root)
{
if (root == NULL)
return;
inorder(root->left);
cout << root->info << " ";
inorder(root->right);
}
int main()
{
struct treenode* root = NULL;
root = create();
mirrortree(root);
cout << "\nInorder of the mirror tree is = ";
inorder(root);
return 0;
}
|
Java
import java.util.Scanner;
class TreeNode {
int info;
TreeNode left, right;
TreeNode(int info) {
this.info = info;
left = right = null;
}
}
public class Main {
static TreeNode create() {
Scanner scanner = new Scanner(System.in);
int data;
TreeNode tree;
System.out.print("\nEnter data to be inserted or type -1 for no insertion: ");
data = scanner.nextInt();
if (data == -1)
return null;
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;
}
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;
}
}
static void inorder(TreeNode root) {
if (root == null)
return;
inorder(root.left);
System.out.print(root.info + " ");
inorder(root.right);
}
public static void main(String[] args) {
TreeNode root;
root = create();
mirrorTree(root);
System.out.print("\nInorder of the mirror tree is = ");
inorder(root);
}
}
|
Output:

Time Complexity: O(N)
Auxiliary Space: O(1)
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>
using namespace std;
struct treenode {
int info;
struct treenode *left, *right;
};
struct treenode* create()
{
int data;
struct treenode* tree;
tree = new treenode;
cout << "\nEnter data to be inserted or type -1 for no insertion : ";
cin >> data;
if (data == -1)
return 0;
tree->info = data;
cout << "Enter left child of : " << data;
tree->left = create();
cout << "Enter right child of : " << data;
tree->right = create();
return tree;
};
void serialize(struct treenode* root,
vector<int>& v)
{
if (root == NULL) {
v.push_back(-1);
return;
}
v.push_back(root->info);
serialize(root->left, v);
serialize(root->right, v);
}
int main()
{
struct treenode* root = NULL;
root = create();
vector<int> v;
serialize(root, v);
cout << "\nSerialize form of the tree is = ";
for (int i = 0; i < v.size(); i++)
cout << v[i] << " ";
return 0;
}
|
Java
import java.util.*;
class TreeNode {
int info;
TreeNode left, right;
TreeNode(int item)
{
info = item;
left = right = null;
}
}
class SerializeDeserializeBinaryTree {
public static TreeNode create()
{
int data;
TreeNode tree;
tree = new TreeNode(0);
Scanner sc = new Scanner(System.in);
System.out.print(
"\nEnter data to be inserted or type -1 for no insertion : ");
data = sc.nextInt();
if (data == -1)
return null;
tree.info = 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;
}
public static void serialize(TreeNode root,
List<Integer> v)
{
if (root == null) {
v.add(-1);
return;
}
v.add(root.info);
serialize(root.left, v);
serialize(root.right, v);
}
public static void main(String args[])
{
TreeNode root = null;
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) + " ");
}
}
|
Output:

Time Complexity: O(N)
Auxiliary Space: O(N)
Complexity Analysis:
- Time Complexity: O(n).
- Auxiliary Space: O(1).
Feeling lost in the world of random DSA topics, wasting time without progress? It's time for a change! Join our DSA course, where we'll guide you on an exciting journey to master DSA efficiently and on schedule.
Ready to dive in? Explore our Free Demo Content and join our DSA course, trusted by over 100,000 geeks!
Commit to GfG's Three-90 Challenge! Purchase a course, complete 90% in 90 days, and save 90% cost click here to explore.
Last Updated :
17 Jan, 2024
Like Article
Save Article
Share your thoughts in the comments
Please Login to comment...