Introduction to Binary Tree
Last Updated :
12 Dec, 2024
Binary Tree is a non-linear and hierarchical data structure where each node has at most two children referred to as the left child and the right child. The topmost node in a binary tree is called the root, and the bottom-most nodes are called leaves.

Introduction to Binary Tree
Representation of Binary Tree
Each node in a Binary Tree has three parts:
- Data
- Pointer to the left child
- Pointer to the right child

Binary Tree Representation
Create/Declare a Node of a Binary Tree
Syntax to declare a Node of Binary Tree in different languages:
C++
// Use any below method to implement Nodes of binary tree
// 1: Using struct
struct Node {
int data;
Node* left, * right;
Node(int key) {
data = key;
left = nullptr;
right = nullptr;
}
};
// 2: Using class
class Node {
public:
int data;
Node* left, * right;
Node(int key) {
data = key;
left = nullptr;
right = nullptr;
}
};
C
// Structure of each node of the tree.
struct Node {
int data;
struct Node* left;
struct Node* right;
};
// Note : Unlike other languages, C does not support
// Object Oriented Programming. So we need to write
// a separat method for create and instance of tree node
struct Node* newNode(int item) {
struct Node* temp =
(struct Node*)malloc(sizeof(struct Node));
temp->key = item;
temp->left = temp->right = NULL;
return temp;
}
Java
// Class containing left and right child
// of current node and key value
class Node {
int key;
Node left, right;
public Node(int item)
{
key = item;
left = right = null;
}
}
Python
# A Python class that represents
# an individual node in a Binary Tree
class Node:
def __init__(self, key):
self.left = None
self.right = None
self.val = key
C#
// Class containing left and right child
// of current node and key value
class Node {
int key;
Node left, right;
public Node(int item)
{
key = item;
left = right = null;
}
}
JavaScript
/* Class containing left and right child
of current node and data*/
class Node
{
constructor(item)
{
this.data = item;
this.left = this.right = null;
}
}
Example for Creating a Binary Tree
Here’s an example of creating a Binary Tree with four nodes (2, 3, 4, 5)

Creating a Binary Tree having three nodes
C++
#include <iostream>
using namespace std;
struct Node{
int data;
Node *left, *right;
Node(int d){
data = d;
left = nullptr;
right = nullptr;
}
};
int main(){
// Initilize and allocate memory for tree nodes
Node* firstNode = new Node(2);
Node* secondNode = new Node(3);
Node* thirdNode = new Node(4);
Node* fourthNode = new Node(5);
// Connect binary tree nodes
firstNode->left = secondNode;
firstNode->right = thirdNode;
secondNode->left = fourthNode;
return 0;
}
C
#include <stdio.h>
#include <stdlib.h>
struct Node {
int data;
struct Node *left;
struct Node *right;
};
struct Node* createNode(int d) {
struct Node* newNode =
(struct Node*)malloc(sizeof(struct Node));
newNode->data = d;
newNode->left = NULL;
newNode->right = NULL;
return newNode;
}
int main() {
// Initialize and allocate memory for tree nodes
struct Node* firstNode = createNode(2);
struct Node* secondNode = createNode(3);
struct Node* thirdNode = createNode(4);
struct Node* fourthNode = createNode(5);
// Connect binary tree nodes
firstNode->left = secondNode;
firstNode->right = thirdNode;
secondNode->left = fourthNode;
return 0;
}
Java
class Node {
int data;
Node left, right;
Node(int d) {
data = d;
left = null;
right = null;
}
}
class GfG {
public static void main(String[] args) {
// Initialize and allocate memory for tree nodes
Node firstNode = new Node(2);
Node secondNode = new Node(3);
Node thirdNode = new Node(4);
Node fourthNode = new Node(5);
// Connect binary tree nodes
firstNode.left = secondNode;
firstNode.right = thirdNode;
secondNode.left = fourthNode;
}
}
Python
class Node:
def __init__(self, d):
self.data = d
self.left = None
self.right = None
# Initialize and allocate memory for tree nodes
firstNode = Node(2)
secondNode = Node(3)
thirdNode = Node(4)
fourthNode = Node(5)
# Connect binary tree nodes
firstNode.left = secondNode
firstNode.right = thirdNode
secondNode.left = fourthNode
C#
using System;
class Node {
public int data;
public Node left, right;
public Node(int d) {
this.data = d;
left = null;
right = null;
}
}
class GfG {
static void Main() {
// Initialize and allocate memory for tree nodes
Node firstNode = new Node(2);
Node secondNode = new Node(3);
Node thirdNode = new Node(4);
Node fourthNode = new Node(5);
// Connect binary tree nodes
firstNode.left = secondNode;
firstNode.right = thirdNode;
secondNode.left = fourthNode;
}
}
JavaScript
class Node {
constructor(d) {
this.data = d;
this.left = null;
this.right = null;
}
}
// Initialize and allocate memory for tree nodes
let firstNode = new Node(2);
let secondNode = new Node(3);
let thirdNode = new Node(4);
let fourthNode = new Node(5);
// Connect binary tree nodes
firstNode.left = secondNode;
firstNode.right = thirdNode;
secondNode.left = fourthNode;
In the above code, we have created four tree nodes firstNode, secondNode, thirdNode and fourthNode having values 2, 3, 4 and 5 respectively.
- After creating three nodes, we have connected these node to form the tree structure like mentioned in above image.
- Connect the secondNode to the left of firstNode by firstNode->left = secondNode
- Connect the thirdNode to the right of firstNode by firstNode->right = thirdNode
- Connect the fourthNode to the left of secondNode by secondNode->left = fourthNode
Terminologies in Binary Tree
- Nodes: The fundamental part of a binary tree, where each node contains data and link to two child nodes.
- Root: The topmost node in a tree is known as the root node. It has no parent and serves as the starting point for all nodes in the tree.
- Parent Node: A node that has one or more child nodes. In a binary tree, each node can have at most two children.
- Child Node: A node that is a descendant of another node (its parent).
- Leaf Node: A node that does not have any children or both children are null.
- Internal Node: A node that has at least one child. This includes all nodes except the root and the leaf nodes.
- Depth of a Node: The number of edges from a specific node to the root node. The depth of the root node is zero.
- Height of a Binary Tree: The number of nodes from the deepest leaf node to the root node.
The diagram below shows all these terms in a binary tree.

Terminologies in Binary Tree in Data Structure
Properties of Binary Tree
- The maximum number of nodes at level L of a binary tree is 2L
- The maximum number of nodes in a binary tree of height H is 2H – 1
- Total number of leaf nodes in a binary tree = total number of nodes with 2 children + 1
- In a Binary Tree with N nodes, the minimum possible height or the minimum number of levels is Log2(N+1)
- A Binary Tree with L leaves has at least | Log2L |+ 1 levels
Please refer Properties of Binary Tree for more details.
Types of Binary Tree
Binary Tree can be classified into multiples types based on multiple factors:
- On the basis of Number of Children
- On the basis of Completion of Levels
- On the basis of Node Values:
Operations On Binary Tree
Following is a list of common operations that can be performed on a binary tree:
1. Traversal in Binary Tree
Traversal in Binary Tree involves visiting all the nodes of the binary tree. Tree Traversal algorithms can be classified broadly into two categories, DFS and BFS:
Depth-First Search (DFS) algorithms: DFS explores as far down a branch as possible before backtracking. It is implemented using recursion. The main traversal methods in DFS for binary trees are:
Breadth-First Search (BFS) algorithms: BFS explores all nodes at the present depth before moving on to nodes at the next depth level. It is typically implemented using a queue. BFS in a binary tree is commonly referred to as Level Order Traversal.
Below is the implementation of traversals algorithm in binary tree:
C++
#include <bits/stdc++.h>
using namespace std;
struct Node {
int data;
Node* left, * right;
Node(int d) {
data = d;
left = nullptr;
right = nullptr;
}
};
// In-order DFS: Left, Root, Right
void inOrderDFS(Node* node) {
if (node == nullptr) return;
inOrderDFS(node->left);
cout << node->data << " ";
inOrderDFS(node->right);
}
// Pre-order DFS: Root, Left, Right
void preOrderDFS(Node* node) {
if (node == nullptr) return;
cout << node->data << " ";
preOrderDFS(node->left);
preOrderDFS(node->right);
}
// Post-order DFS: Left, Right, Root
void postOrderDFS(Node* node) {
if (node == nullptr) return;
postOrderDFS(node->left);
postOrderDFS(node->right);
cout << node->data << " ";
}
void BFS(Node* root) {
if (root == nullptr) return;
queue<Node*> q;
q.push(root);
while (!q.empty()) {
Node* node = q.front();
q.pop();
cout << node->data << " ";
if (node->left != nullptr) q.push(node->left);
if (node->right != nullptr) q.push(node->right);
}
}
int main() {
Node* root = new Node(2);
root->left = new Node(3);
root->right = new Node(4);
root->left->left = new Node(5);
cout << "In-order DFS: ";
inOrderDFS(root);
cout << "\nPre-order DFS: ";
preOrderDFS(root);
cout << "\nPost-order DFS: ";
postOrderDFS(root);
cout << "\nLevel order: ";
BFS(root);
return 0;
}
C
#include <stdio.h>
#include <stdlib.h>
struct Node{
int data;
struct Node *left;
struct Node *right;
};
// In-order DFS: Left, Root, Right
void inOrderDFS(struct Node *node){
if (node == NULL) return;
inOrderDFS(node->left);
printf("%d ", node->data);
inOrderDFS(node->right);
}
// Pre-order DFS: Root, Left, Right
void preOrderDFS(struct Node *node){
if (node == NULL) return;
printf("%d ", node->data);
preOrderDFS(node->left);
preOrderDFS(node->right);
}
// Post-order DFS: Left, Right, Root
void postOrderDFS(struct Node *node){
if (node == NULL) return;
postOrderDFS(node->left);
postOrderDFS(node->right);
printf("%d ", node->data);
}
// BFS: Level order traversal
void BFS(struct Node *root){
if (root == NULL) return;
struct Node *queue[100];
int front = 0, rear = 0;
queue[rear++] = root;
while (front < rear) {
struct Node *node = queue[front++];
printf("%d ", node->data);
if (node->left)
queue[rear++] = node->left;
if (node->right)
queue[rear++] = node->right;
}
}
struct Node *createNode(int d){
struct Node *newNode =
(struct Node *)malloc(sizeof(struct Node));
newNode->data = d;
newNode->left = NULL;
newNode->right = NULL;
return newNode;
}
int main(){
// Creating the tree
struct Node *root = (struct Node *)malloc(sizeof(struct Node));
root->data = 2;
root->left = (struct Node *)malloc(sizeof(struct Node));
root->left->data = 3;
root->right = (struct Node *)malloc(sizeof(struct Node));
root->right->data = 4;
root->left->left = (struct Node *)malloc(sizeof(struct Node));
root->left->left->data = 5;
printf("In-order DFS: ");
inOrderDFS(root);
printf("\nPre-order DFS: ");
preOrderDFS(root);
printf("\nPost-order DFS: ");
postOrderDFS(root);
printf("\nLevel order: ");
BFS(root);
return 0;
}
Java
import java.util.LinkedList;
import java.util.Queue;
class Node {
int data;
Node left, right;
Node(int d) {
data = d;
left = right = null;
}
}
// BinaryTree class
class GfG {
// In-order DFS: Left, Root, Right
static void inOrderDFS(Node node) {
if (node == null) return;
inOrderDFS(node.left);
System.out.print(node.data + " ");
inOrderDFS(node.right);
}
// Pre-order DFS: Root, Left, Right
static void preOrderDFS(Node node) {
if (node == null) return;
System.out.print(node.data + " ");
preOrderDFS(node.left);
preOrderDFS(node.right);
}
// Post-order DFS: Left, Right, Root
static void postOrderDFS(Node node) {
if (node == null) return;
postOrderDFS(node.left);
postOrderDFS(node.right);
System.out.print(node.data + " ");
}
// BFS: Level order traversal
static void BFS(Node root) {
if (root == null) return;
Queue<Node> queue = new LinkedList<>();
queue.add(root);
while (!queue.isEmpty()) {
Node node = queue.poll();
System.out.print(node.data + " ");
if (node.left != null) queue.add(node.left);
if (node.right != null) queue.add(node.right);
}
}
public static void main(String[] args) {
// Creating the tree
Node root = new Node(2);
root.left = new Node(3);
root.right = new Node(4);
root.left.left = new Node(5);
System.out.print("In-order DFS: ");
inOrderDFS(root);
System.out.print("\nPre-order DFS: ");
preOrderDFS(root);
System.out.print("\nPost-order DFS: ");
postOrderDFS(root);
System.out.print("\nLevel order: ");
BFS(root);
}
}
Python
class Node:
def __init__(self, data):
self.data = data
self.left = None
self.right = None
# In-order DFS: Left, Root, Right
def in_order_dfs(node):
if node is None:
return
in_order_dfs(node.left)
print(node.data, end=' ')
in_order_dfs(node.right)
# Pre-order DFS: Root, Left, Right
def pre_order_dfs(node):
if node is None:
return
print(node.data, end=' ')
pre_order_dfs(node.left)
pre_order_dfs(node.right)
# Post-order DFS: Left, Right, Root
def post_order_dfs(node):
if node is None:
return
post_order_dfs(node.left)
post_order_dfs(node.right)
print(node.data, end=' ')
# BFS: Level order traversal
def bfs(root):
if root is None:
return
queue = [root]
while queue:
node = queue.pop(0)
print(node.data, end=' ')
if node.left:
queue.append(node.left)
if node.right:
queue.append(node.right)
if __name__ == "__main__":
# Creating the tree
root = Node(2)
root.left = Node(3)
root.right = Node(4)
root.left.left = Node(5)
print("In-order DFS: ", end='')
in_order_dfs(root)
print("\nPre-order DFS: ", end='')
pre_order_dfs(root)
print("\nPost-order DFS: ", end='')
post_order_dfs(root)
print("\nLevel order: ", end='')
bfs(root)
C#
using System;
using System.Collections.Generic;
class Node {
public int data;
public Node left, right;
public Node(int d) {
data = d;
left = right = null;
}
}
class GfG {
// In-order DFS: Left, Root, Right
static void InOrderDFS(Node node) {
if (node == null) return;
InOrderDFS(node.left);
Console.Write(node.data + " ");
InOrderDFS(node.right);
}
// Pre-order DFS: Root, Left, Right
static void PreOrderDFS(Node node) {
if (node == null) return;
Console.Write(node.data + " ");
PreOrderDFS(node.left);
PreOrderDFS(node.right);
}
// Post-order DFS: Left, Right, Root
static void PostOrderDFS(Node node) {
if (node == null) return;
PostOrderDFS(node.left);
PostOrderDFS(node.right);
Console.Write(node.data + " ");
}
// BFS: Level order traversal
static public void BFS(Node root) {
if (root == null) return;
Queue<Node> queue = new Queue<Node>();
queue.Enqueue(root);
while (queue.Count > 0) {
Node node = queue.Dequeue();
Console.Write(node.data + " ");
if (node.left != null) queue.Enqueue(node.left);
if (node.right != null) queue.Enqueue(node.right);
}
}
public static void Main(string[] args) {
// Creating the tree
Node root = new Node(2);
root.left = new Node(3);
root.right = new Node(4);
root.left.left = new Node(5);
Console.Write("In-order DFS: ");
InOrderDFS(root);
Console.Write("\nPre-order DFS: ");
PreOrderDFS(root);
Console.Write("\nPost-order DFS: ");
PostOrderDFS(root);
Console.Write("\nLevel order: ");
BFS(root);
}
}
JavaScript
// Node structure
class Node {
constructor(data) {
this.data = data;
this.left = null;
this.right = null;
}
}
// In-order DFS: Left, Root, Right
function inOrderDFS(node) {
if (node === null) return;
inOrderDFS(node.left);
process.stdout.write(node.data + " ");
inOrderDFS(node.right);
}
// Pre-order DFS: Root, Left, Right
function preOrderDFS(node) {
if (node === null) return;
process.stdout.write(node.data + " ");
preOrderDFS(node.left);
preOrderDFS(node.right);
}
// Post-order DFS: Left, Right, Root
function postOrderDFS(node) {
if (node === null) return;
postOrderDFS(node.left);
postOrderDFS(node.right);
process.stdout.write(node.data + " ");
}
// BFS: Level order traversal
function bfs(root) {
if (root === null) return;
let queue = [root];
while (queue.length > 0) {
let node = queue.shift();
process.stdout.write(node.data + " ");
if (node.left) queue.push(node.left);
if (node.right) queue.push(node.right);
}
}
// Creating the tree
let root = new Node(2);
root.left = new Node(3);
root.right = new Node(4);
root.left.left = new Node(5);
console.log("In-order DFS: ");
inOrderDFS(root);
console.log("\nPre-order DFS: ");
preOrderDFS(root);
console.log("\nPost-order DFS: ");
postOrderDFS(root);
console.log("\nLevel order: ");
bfs(root);
OutputIn-order DFS: 5 3 2 4
Pre-order DFS: 2 3 5 4
Post-order DFS: 5 3 4 2
Level order: 2 3 4 5
2. Insertion in Binary Tree
Inserting elements means add a new node into the binary tree. As we know that there is no such ordering of elements in the binary tree, So we do not have to worry about the ordering of node in the binary tree. We would first creates a root node in case of empty tree. Then subsequent insertions involve iteratively searching for an empty place at each level of the tree. When an empty left or right child is found then new node is inserted there. By convention, insertion always starts with the left child node.

Insertion in Binary Tree
C++
#include <bits/stdc++.h>
using namespace std;
struct Node {
int data;
Node* left, * right;
Node(int d) {
data = d;
left = right = nullptr;
}
};
// Function to insert a new node in the binary tree
Node* insert(Node* root, int key) {
// If the tree is empty, create the root node
if (root == nullptr) {
root = new Node(key);
return root;
}
// Create a queue for level order traversal
queue<Node*> q;
q.push(root);
// Do level order traversal until we find an empty place
while (!q.empty()) {
Node* temp = q.front();
q.pop();
// If left child is empty, insert the new node here
if (temp->left == nullptr) {
temp->left = new Node(key);
break;
} else {
q.push(temp->left);
}
// If right child is empty, insert the new node here
if (temp->right == nullptr) {
temp->right = new Node(key);
break;
} else {
q.push(temp->right);
}
}
return root;
}
void inorder(Node* root) {
if (root == nullptr) return;
inorder(root->left);
cout << root->data << " ";
inorder(root->right);
}
int main() {
Node* root = new Node(2);
root->left = new Node(3);
root->right = new Node(4) ;
root->left->left = new Node(5);
cout << "Inorder traversal before insertion: ";
inorder(root);
cout << endl;
int key = 6;
root = insert(root, key);
cout << "Inorder traversal after insertion: ";
inorder(root);
cout << endl;
return 0;
}
C
#include <stdio.h>
#include <stdlib.h>
struct Node {
int data;
struct Node* left;
struct Node* right;
};
struct Node* createNode(int d);
// Function to insert a new node in the binary tree
struct Node* insert(struct Node* root, int key) {
if (root == NULL) return createNode(key);
// Create a queue for level order traversal
struct Node* queue[100];
int front = 0, rear = 0;
queue[rear++] = root;
while (front < rear) {
struct Node* temp = queue[front++];
// If left child is empty, insert the new node here
if (temp->left == NULL) {
temp->left = createNode(key);
break;
} else {
queue[rear++] = temp->left;
}
// If right child is empty, insert the new node here
if (temp->right == NULL) {
temp->right = createNode(key);
break;
} else {
queue[rear++] = temp->right;
}
}
return root;
}
void inorder(struct Node* root) {
if (root == NULL) return;
inorder(root->left);
printf("%d ", root->data);
inorder(root->right);
}
struct Node* createNode(int d) {
struct Node* newNode =
(struct Node*)malloc(sizeof(struct Node));
newNode->data = d;
newNode->left = NULL;
newNode->right = NULL;
return newNode;
}
int main() {
struct Node* root = createNode(2);
root->left = createNode(3);
root->right = createNode(4);
root->left->left = createNode(5);
printf("Inorder traversal before insertion: ");
inorder(root);
printf("\n");
int key = 6;
root = insert(root, key);
printf("Inorder traversal after insertion: ");
inorder(root);
printf("\n");
return 0;
}
Java
import java.util.LinkedList;
import java.util.Queue;
class Node {
int data;
Node left, right;
Node(int d) {
data = d;
left = right = null;
}
}
class GfG {
// Function to insert a new node in the binary tree
static Node insert(Node root, int key) {
if (root == null) return new Node(key);
// Create a queue for level order traversal
Queue<Node> q = new LinkedList<>();
q.add(root);
while (!q.isEmpty()) {
Node temp = q.poll();
// If left child is empty, insert the new node here
if (temp.left == null) {
temp.left = new Node(key);
break;
} else {
q.add(temp.left);
}
// If right child is empty, insert the new node here
if (temp.right == null) {
temp.right = new Node(key);
break;
} else {
q.add(temp.right);
}
}
return root;
}
// In-order traversal
static void inorder(Node root) {
if (root == null) return;
inorder(root.left);
System.out.print(root.data + " ");
inorder(root.right);
}
public static void main(String[] args) {
Node root = new Node(2);
root.left = new Node(3);
root.right = new Node(4);
root.left.left = new Node(5);
System.out.print("Inorder traversal before insertion: ");
inorder(root);
System.out.println();
int key = 6;
root = insert(root, key);
System.out.print("Inorder traversal after insertion: ");
inorder(root);
System.out.println();
}
}
Python
from collections import deque
class Node:
def __init__(self, d):
self.data = d
self.left = None
self.right = None
# Function to insert a new node in the binary tree
def insert(root, key):
if root is None:
return Node(key)
# Create a queue for level order traversal
queue = deque([root])
while queue:
temp = queue.popleft()
# If left child is empty, insert the new node here
if temp.left is None:
temp.left = Node(key)
break
else:
queue.append(temp.left)
# If right child is empty, insert the new node here
if temp.right is None:
temp.right = Node(key)
break
else:
queue.append(temp.right)
return root
# In-order traversal
def inorder(root):
if root is None:
return
inorder(root.left)
print(root.data, end=" ")
inorder(root.right)
if __name__ == "__main__":
root = Node(2)
root.left = Node(3)
root.right = Node(4)
root.left.left = Node(5)
print("Inorder traversal before insertion: ", end="")
inorder(root)
print()
key = 6
root = insert(root, key)
print("Inorder traversal after insertion: ", end="")
inorder(root)
print()
C#
using System;
using System.Collections.Generic;
class Node {
public int data;
public Node left, right;
public Node(int d) {
data = d;
left = right = null;
}
}
class GfG {
// Function to insert a new node in the binary tree
static Node Insert(Node root, int key) {
if (root == null) {
return new Node(key);
}
// Create a queue for level order traversal
Queue<Node> q = new Queue<Node>();
q.Enqueue(root);
while (q.Count > 0) {
Node temp = q.Dequeue();
// If left child is empty, insert the new node here
if (temp.left == null) {
temp.left = new Node(key);
break;
} else {
q.Enqueue(temp.left);
}
// If right child is empty, insert the new node here
if (temp.right == null) {
temp.right = new Node(key);
break;
} else {
q.Enqueue(temp.right);
}
}
return root;
}
// In-order traversal
static void Inorder(Node root) {
if (root == null) return;
Inorder(root.left);
Console.Write(root.data + " ");
Inorder(root.right);
}
static void Main() {
Node root = new Node(2);
root.left = new Node(3);
root.right = new Node(4);
root.left.left = new Node(5);
Console.Write("Inorder traversal before insertion: ");
Inorder(root);
Console.WriteLine();
int key = 6;
root = Insert(root, key);
Console.Write("Inorder traversal after insertion: ");
Inorder(root);
Console.WriteLine();
}
}
JavaScript
class Node {
constructor(d) {
this.data = d;
this.left = null;
this.right = null;
}
}
// Function to insert a new node in the binary tree
function insert(root, key) {
if (root === null) {
return new Node(key);
}
// Create a queue for level order traversal
let queue = [root];
while (queue.length > 0) {
let temp = queue.shift();
// If left child is empty, insert the new node here
if (temp.left === null) {
temp.left = new Node(key);
break;
} else {
queue.push(temp.left);
}
// If right child is empty, insert the new node here
if (temp.right === null) {
temp.right = new Node(key);
break;
} else {
queue.push(temp.right);
}
}
return root;
}
// In-order traversal
function inorder(root) {
if (root === null) return;
inorder(root.left);
process.stdout.write(root.data + " ");
inorder(root.right);
}
let root = new Node(2);
root.left = new Node(3);
root.right = new Node(4);
root.left.left = new Node(5);
console.log("Inorder traversal before insertion: ");
inorder(root);
console.log();
let key = 6;
root = insert(root, key);
console.log("Inorder traversal after insertion: ");
inorder(root);
console.log();
OutputInorder traversal before insertion: 5 3 2 4
Inorder traversal after insertion: 5 3 6 2 4
3. Searching in Binary Tree
Searching for a value in a binary tree means looking through the tree to find a node that has that value. Since binary trees do not have a specific order like binary search trees, we typically use any traversal method to search. The most common methods are depth-first search (DFS) and breadth-first search (BFS). In DFS, we start from the root and explore the depth nodes first. In BFS, we explore all the nodes at the present depth level before moving on to the nodes at the next level. We continue this process until we either find the node with the desired value or reach the end of the tree. If the tree is empty or the value isn’t found after exploring all possibilities, we conclude that the value does not exist in the tree.
Here is the implementation of searching in a binary tree using Depth-First Search (DFS)
C++
#include <iostream>
using namespace std;
struct Node{
int data;
Node *left, *right;
Node(int d){
data = d;
left = right = nullptr;
}
};
// Function to search for a value in the binary tree using DFS
bool searchDFS(Node *root, int value){
// Base case: If the tree is empty or we've reached a leaf node
if (root == nullptr) return false;
// If the node's data is equal to the value we are searching for
if (root->data == value) return true;
// Recursively search in the left and right subtrees
bool left_res = searchDFS(root->left, value);
bool right_res = searchDFS(root->right, value);
return left_res || right_res;
}
int main()
{
Node *root = new Node(2);
root->left = new Node(3);
root->right = new Node(4);
root->left->left = new Node(5);
root->left->right = new Node(6);
int value = 6;
if (searchDFS(root, value))
cout << value << " is found in the binary tree" << endl;
else
cout << value << " is not found in the binary tree" << endl;
return 0;
}
C
#include <stdio.h>
#include <stdlib.h>
struct Node {
int data;
struct Node* left;
struct Node* right;
};
// Function to search for a value in the binary tree using DFS
int searchDFS(struct Node* root, int value) {
// Base case: If the tree is empty or we've reached a leaf node
if (root == NULL) return 0;
// If the node's data is equal to the value we are searching for
if (root->data == value) return 1;
// Recursively search in the left and right subtrees
int left_res = searchDFS(root->left, value);
int right_res = searchDFS(root->right, value);
return left_res || right_res;
}
struct Node* createNode(int d) {
struct Node* node =
(struct Node*)malloc(sizeof(struct Node));
node->data = d;
node->left = node->right = NULL;
return node;
}
int main() {
struct Node* root = createNode(2);
root->left = createNode(3);
root->right = createNode(4);
root->left->left = createNode(5);
root->left->right = createNode(6);
int value = 6;
if (searchDFS(root, value))
printf("%d is found in the binary tree\n", value);
else
printf("%d is not found in the binary tree\n", value);
return 0;
}
Java
class Node {
int data;
Node left, right;
Node(int d){
data = d;
left = right = null;
}
}
public class GFG {
// Function to search for a value in the binary tree
// using DFS
static boolean searchDFS(Node root, int value){
// Base case: If the tree is empty or we've reached
// a leaf node
if (root == null) return false;
// If the node's data is equal to the value we are
// searching for
if (root.data == value) return true;
// Recursively search in the left and right subtrees
boolean left_res = searchDFS(root.left, value);
boolean right_res = searchDFS(root.right, value);
return left_res || right_res;
}
public static void main(String[] args){
Node root = new Node(2);
root.left = new Node(3);
root.right = new Node(4);
root.left.left = new Node(5);
root.left.right = new Node(6);
int value = 6;
if (searchDFS(root, value))
System.out.println(
value + " is found in the binary tree");
else
System.out.println(
value + " is not found in the binary tree");
}
}
Python
class Node:
def __init__(self, d):
self.data = d
self.left = None
self.right = None
# Function to search for a value in the binary tree using DFS
def searchDFS(root, value):
# Base case: If the tree is empty or we've reached a leaf node
if root is None:
return False
# If the node's data is equal to the value we are searching for
if root.data == value:
return True
# Recursively search in the left and right subtrees
left_res = searchDFS(root.left, value)
right_res = searchDFS(root.right, value)
return left_res or right_res
if __name__ == "__main__":
root = Node(2)
root.left = Node(3)
root.right = Node(4)
root.left.left = Node(5)
root.left.right = Node(6)
value = 6
if searchDFS(root, value):
print(f"{value} is found in the binary tree")
else:
print(f"{value} is not found in the binary tree")
C#
using System;
class Node {
public int data;
public Node left, right;
public Node(int d){
data = d;
left = right = null;
}
}
class GFG {
// Function to search for a value in the binary tree
// using DFS
static bool SearchDFS(Node root, int value){
// Base case: If the tree is empty or we've reached
// a leaf node
if (root == null) return false;
// If the node's data is equal to the value we are
// searching for
if (root.data == value) return true;
// Recursively search in the left and right subtrees
bool left_res = SearchDFS(root.left, value);
bool right_res = SearchDFS(root.right, value);
return left_res || right_res;
}
static void Main(string[] args){
Node root = new Node(2);
root.left = new Node(3);
root.right = new Node(4);
root.left.left = new Node(5);
root.left.right = new Node(6);
int value = 6;
if (SearchDFS(root, value))
Console.WriteLine(String.Format(
"{0} is found in the binary tree", value));
else
Console.WriteLine(String.Format(
"{0} is not found in the binary tree",
value));
}
}
JavaScript
class Node {
constructor(d) {
this.data = d;
this.left = null;
this.right = null;
}
}
// Function to search for a value in the binary tree using DFS
function searchDFS(root, value) {
// Base case: If the tree is empty or we've reached a leaf node
if (root === null) {
return false;
}
// If the node's data is equal to the value we are searching for
if (root.data === value) {
return true;
}
// Recursively search in the left and right subtrees
const left_res = searchDFS(root.left, value);
const right_res = searchDFS(root.right, value);
return left_res || right_res;
}
// Creating the binary tree
const root = new Node(2);
root.left = new Node(3);
root.right = new Node(4);
root.left.left = new Node(5);
root.left.right = new Node(6);
const value = 6;
if (searchDFS(root, value)) {
console.log(`${value} is found in the binary tree`);
} else {
console.log(`${value} is not found in the binary tree`);
}
Output6 is found in the binary tree
4. Deletion in Binary Tree
Deleting a node from a binary tree means removing a specific node while keeping the tree’s structure. First, we need to find the node that want to delete by traversing through the tree using any traversal method. Then replace the node’s value with the value of the last node in the tree (found by traversing to the rightmost leaf), and then delete that last node. This way, the tree structure won’t be effected. And remember to check for special cases, like trying to delete from an empty tree, to avoid any issues.
Note: There is no specific rule of deletion but we always make sure that during deletion the binary tree proper should be preserved.

Deletion in Binary Tree
C++
#include <bits/stdc++.h>
using namespace std;
struct Node {
int data;
Node* left, * right;
Node(int d) {
data = d;
left = right = nullptr;
}
};
// Function to delete a node from the binary tree
Node* deleteNode(Node* root, int val) {
if (root == nullptr) return nullptr;
// Use a queue to perform BFS
queue<Node*> q;
q.push(root);
Node* target = nullptr;
// Find the target node
while (!q.empty()) {
Node* curr = q.front();
q.pop();
// Check for current node is the target node to delete
if (curr->data == val) {
target = curr;
break;
}
// Add children to the queue
if (curr->left) q.push(curr->left);
if (curr->right) q.push(curr->right);
}
// If target node is not found, return the original tree
if (target == nullptr) return root;
// Find the deepest rightmost node and its parent
pair<Node*, Node*> last = {nullptr, nullptr};
queue<pair<Node*, Node*>> q1;
q1.push({root, nullptr});
while (!q1.empty()) {
auto curr = q1.front();
q1.pop();
// Update the last
last = curr;
if (curr.first->left)
q1.push({curr.first->left, curr.first});
if (curr.first->right)
q1.push({curr.first->right, curr.first});
}
Node* lastNode = last.first;
Node* lastParent = last.second;
// Replace target's value with the last node's value
target->data = lastNode->data;
// Remove the last node
if (lastParent) {
if (lastParent->left==lastNode)lastParent->left = nullptr;
else lastParent->right = nullptr;
delete lastNode;
} else {
// If the last node was the root
delete lastNode;
return nullptr;
}
return root;
}
void inOrder(Node* root) {
if (root == nullptr) return;
inOrder(root->left);
cout << root->data << " ";
inOrder(root->right);
}
int main() {
// Creating a simple binary tree
Node *root = new Node(2);
root->left = new Node(3);
root->right = new Node(4);
root->left->left = new Node(5);
root->left->right = new Node(6);
cout << "Original tree (in-order): ";
inOrder(root);
int valToDel = 3;
root = deleteNode(root, valToDel);
cout <<"\nTree after deleting " << valToDel << " (in-order): ";
inOrder(root);
cout << endl;
return 0;
}
C
#include <stdio.h>
#include <stdlib.h>
struct Node {
int data;
struct Node* left;
struct Node* right;
};
struct Node* createNode(int d);
// Function to delete a node from the binary tree
struct Node* deleteNode(struct Node* root, int val) {
if (root == NULL) return NULL;
// Use a queue to perform BFS
struct Node* queue[100];
int front = 0, rear = 0;
queue[rear++] = root;
struct Node* target = NULL;
// Find the target node
while (front < rear) {
struct Node* curr = queue[front++];
if (curr->data == val) {
target = curr;
break;
}
if (curr->left) queue[rear++] = curr->left;
if (curr->right) queue[rear++] = curr->right;
}
if (target == NULL) return root;
// Find the deepest rightmost node and its parent
struct Node* lastNode = NULL;
struct Node* lastParent = NULL;
struct Node* queue1[100];
int front1 = 0, rear1 = 0;
queue1[rear1++] = root;
struct Node* parents[100];
parents[rear1 - 1] = NULL;
while (front1 < rear1) {
struct Node* curr = queue1[front1];
struct Node* parent = parents[front1++];
lastNode = curr;
lastParent = parent;
if (curr->left) {
queue1[rear1] = curr->left;
parents[rear1++] = curr;
}
if (curr->right) {
queue1[rear1] = curr->right;
parents[rear1++] = curr;
}
}
// Replace target's value with the last node's value
target->data = lastNode->data;
// Remove the last node
if (lastParent) {
if (lastParent->left == lastNode) lastParent->left = NULL;
else lastParent->right = NULL;
free(lastNode);
} else {
free(lastNode);
return NULL;
}
return root;
}
void inorder(struct Node* root) {
if (root == NULL) return;
inorder(root->left);
printf("%d ", root->data);
inorder(root->right);
}
// Function to create a new node
struct Node* createNode(int d) {
struct Node* newNode =
(struct Node*)malloc(sizeof(struct Node));
newNode->data = d;
newNode->left = NULL;
newNode->right = NULL;
return newNode;
}
int main() {
struct Node* root = createNode(2);
root->left = createNode(3);
root->right = createNode(4);
root->left->left = createNode(5);
root->left->right = createNode(6);
printf("Original tree (in-order): ");
inorder(root);
printf("\n");
int valToDel = 3;
root = deleteNode(root, valToDel);
printf("Tree after deleting %d (in-order): ", valToDel);
inorder(root);
printf("\n");
return 0;
}
Java
import java.util.LinkedList;
import java.util.Queue;
class Node {
int data;
Node left, right;
Node(int d) {
data = d;
left = right = null;
}
}
class GfG {
// Function to delete a node from the binary tree
static Node deleteNode(Node root, int val) {
if (root == null) return null;
// Use a queue to perform BFS
Queue<Node> q = new LinkedList<>();
q.add(root);
Node target = null;
// Find the target node
while (!q.isEmpty()) {
Node curr = q.poll();
if (curr.data == val) {
target = curr;
break;
}
if (curr.left != null) q.add(curr.left);
if (curr.right != null) q.add(curr.right);
}
if (target == null) return root;
// Find the deepest rightmost node and its parent
Node lastNode = null;
Node lastParent = null;
Queue<Node> q1 = new LinkedList<>();
Queue<Node> parentQueue = new LinkedList<>();
q1.add(root);
parentQueue.add(null);
while (!q1.isEmpty()) {
Node curr = q1.poll();
Node parent = parentQueue.poll();
lastNode = curr;
lastParent = parent;
if (curr.left != null) {
q1.add(curr.left);
parentQueue.add(curr);
}
if (curr.right != null) {
q1.add(curr.right);
parentQueue.add(curr);
}
}
// Replace target's value with the last node's value
target.data = lastNode.data;
// Remove the last node
if (lastParent != null) {
if (lastParent.left == lastNode) lastParent.left = null;
else lastParent.right = null;
} else {
return null;
}
return root;
}
// In-order traversal
static void inorder(Node root) {
if (root == null) return;
inorder(root.left);
System.out.print(root.data + " ");
inorder(root.right);
}
public static void main(String[] args) {
Node root = new Node(2);
root.left = new Node(3);
root.right = new Node(4);
root.left.left = new Node(5);
root.left.right = new Node(6);
System.out.print("Original tree (in-order): ");
inorder(root);
System.out.println();
int valToDel = 3;
root = deleteNode(root, valToDel);
System.out.print("Tree after deleting " + valToDel + " (in-order): ");
inorder(root);
System.out.println();
}
}
Python
from collections import deque
class Node:
def __init__(self, d):
self.data = d
self.left = None
self.right = None
# Function to delete a node from the binary tree
def deleteNode(root, val):
if root is None:
return None
# Use a queue to perform BFS
queue = deque([root])
target = None
# Find the target node
while queue:
curr = queue.popleft()
if curr.data == val:
target = curr
break
if curr.left:
queue.append(curr.left)
if curr.right:
queue.append(curr.right)
if target is None:
return root
# Find the deepest rightmost node and its parent
last_node = None
last_parent = None
queue = deque([(root, None)])
while queue:
curr, parent = queue.popleft()
last_node = curr
last_parent = parent
if curr.left:
queue.append((curr.left, curr))
if curr.right:
queue.append((curr.right, curr))
# Replace target's value with the last node's value
target.data = last_node.data
# Remove the last node
if last_parent:
if last_parent.left == last_node:
last_parent.left = None
else:
last_parent.right = None
else:
return None
return root
# In-order traversal
def inorder(root):
if root is None:
return
inorder(root.left)
print(root.data, end=" ")
inorder(root.right)
if __name__ == "__main__":
root = Node(2)
root.left = Node(3)
root.right = Node(4)
root.left.left = Node(5)
root.left.right = Node(6)
print("Original tree (in-order): ", end="")
inorder(root)
print()
val_to_del = 3
root = deleteNode(root, val_to_del)
print(f"Tree after deleting {val_to_del} (in-order): ", end="")
inorder(root)
print()
C#
using System;
using System.Collections.Generic;
class Node {
public int data;
public Node left, right;
public Node(int d) {
data = d;
left = right = null;
}
}
class GfG {
// Function to delete a node from the binary tree
static Node DeleteNode(Node root, int val) {
if (root == null) return null;
// Use a queue to perform BFS
Queue<Node> q = new Queue<Node>();
q.Enqueue(root);
Node target = null;
// Find the target node
while (q.Count > 0) {
Node curr = q.Dequeue();
if (curr.data == val) {
target = curr;
break;
}
if (curr.left != null) q.Enqueue(curr.left);
if (curr.right != null) q.Enqueue(curr.right);
}
if (target == null) return root;
// Find the deepest rightmost node and its parent
Node lastNode = null;
Node lastParent = null;
Queue<(Node, Node)> q1 = new Queue<(Node, Node)>();
q1.Enqueue((root, null));
while (q1.Count > 0) {
var (curr, parent) = q1.Dequeue();
lastNode = curr;
lastParent = parent;
if (curr.left != null) q1.Enqueue((curr.left, curr));
if (curr.right != null) q1.Enqueue((curr.right, curr));
}
// Replace target's value with the last node's value
target.data = lastNode.data;
// Remove the last node
if (lastParent != null) {
if (lastParent.left == lastNode) lastParent.left = null;
else lastParent.right = null;
} else {
return null;
}
return root;
}
// In-order traversal
static void Inorder(Node root) {
if (root == null) return;
Inorder(root.left);
Console.Write(root.data + " ");
Inorder(root.right);
}
static void Main() {
Node root = new Node(2);
root.left = new Node(3);
root.right = new Node(4);
root.left.left = new Node(5);
root.left.right = new Node(6);
Console.Write("Original tree (in-order): ");
Inorder(root);
Console.WriteLine();
int valToDel = 3;
root = DeleteNode(root, valToDel);
Console.Write("Tree after deleting "
+ valToDel + " (in-order): ");
Inorder(root);
Console.WriteLine();
}
}
JavaScript
class Node {
constructor(d) {
this.data = d;
this.left = null;
this.right = null;
}
}
// Function to delete a node from the binary tree
function deleteNode(root, val) {
if (root === null) return null;
// Use a queue to perform BFS
let queue = [root];
let target = null;
// Find the target node
while (queue.length > 0) {
let curr = queue.shift();
if (curr.data === val) {
target = curr;
break;
}
if (curr.left) queue.push(curr.left);
if (curr.right) queue.push(curr.right);
}
if (target === null) return root;
// Find the deepest rightmost node and its parent
let lastNode = null;
let lastParent = null;
queue = [{ node: root, parent: null }];
while (queue.length > 0) {
let { node: curr, parent } = queue.shift();
lastNode = curr;
lastParent = parent;
if (curr.left) queue.push({ node: curr.left, parent: curr });
if (curr.right) queue.push({ node: curr.right, parent: curr });
}
// Replace target's value with the last node's value
target.data = lastNode.data;
// Remove the last node
if (lastParent) {
if (lastParent.left === lastNode) lastParent.left = null;
else lastParent.right = null;
} else {
return null;
}
return root;
}
// In-order traversal
function inorder(root) {
if (root === null) return;
inorder(root.left);
process.stdout.write(root.data + " ");
inorder(root.right);
}
let root = new Node(2);
root.left = new Node(3);
root.right = new Node(4);
root.left.left = new Node(5);
root.left.right = new Node(6);
console.log("Original tree (in-order): ");
inorder(root);
console.log();
let valToDel = 3;
root = deleteNode(root, valToDel);
console.log(`Tree after deleting ${valToDel} (in-order): `);
inorder(root);
console.log();
OutputOriginal tree (in-order): 5 3 6 2 4
Tree after deleting 3 (in-order): 5 6 2 4
Auxiliary Operations On Binary Tree
Complexity Analysis of Binary Tree Operations
Here’s the complexity analysis for specific binary tree operations:
| Operation | Time Complexity | Auxiliary Space |
|---|
| In-Order Traversal | O(n) | O(n) |
| Pre-Order Traversal | O(n) | O(n) |
| Post-Order Traversal | O(n) | O(n) |
| Insertion (Unbalanced) | O(n) | O(n) |
| Searching (Unbalanced) | O(n) | O(n) |
| Deletion (Unbalanced) | O(n) | O(n) |
Note: We can use Morris Traversal to traverse all the nodes of the binary tree in O(n) time complexity but with O(1) auxiliary space.
Advantages of Binary Tree
- Efficient Search: Binary Search Trees (a variation of Binary Tree) are efficient when searching for a specific element, as each node has at most two child nodes when compared to linked list and arrays
- Memory Efficient: Binary trees require lesser memory as compared to other tree data structures, therefore memory-efficient.
- Binary trees are relatively easy to implement and understand as each node has at most two children, left child and right child.
Disadvantages of Binary Tree
- Limited structure: Binary trees are limited to two child nodes per node, which can limit their usefulness in certain applications. For example, if a tree requires more than two child nodes per node, a different tree structure may be more suitable.
- Unbalanced trees: Unbalanced binary trees, where one subtree is significantly larger than the other, can lead to inefficient search operations. This can occur if the tree is not properly balanced or if data is inserted in a non-random order.
- Space inefficiency: Binary trees can be space inefficient when compared to other data structures like arrays and linked list. This is because each node requires two child references or pointers, which can be a significant amount of memory overhead for large trees.
- Slow performance in worst-case scenarios: In the worst-case scenario, a binary tree can become degenerate or skewed, meaning that each node has only one child. In this case, search operations in Binary Search Tree (a variation of Binary Tree) can degrade to O(n) time complexity, where n is the number of nodes in the tree.
Applications of Binary Tree
- Binary Tree can be used to represent hierarchical data.
- Huffman Coding trees are used in data compression algorithms.
- Priority Queue is another application of binary tree that is used for searching maximum or minimum in O(1) time complexity.
- Useful for indexing segmented at the database is useful in storing cache in the system,
- Binary trees can be used to implement decision trees, a type of machine learning algorithm used for classification and regression analysis.
Frequently Asked Questions (FAQs) on Binary Tree
1. What is a binary tree?
A binary tree is a non-linear data structure consisting of nodes, where each node has at most two children (left child and the right child).
2. What are the types of binary trees?
Binary trees can be classified into various types, including full binary trees, complete binary trees, perfect binary trees, balanced binary trees (such as AVL trees and Red-Black trees), and degenerate (or pathological) binary trees.
3. What is the height of a binary tree?
The height of a binary tree is the length of the longest path from the root node to a leaf node. It represents the number of edges in the longest path from the root node to a leaf node.
4. What is the depth of a node in a binary tree?
The depth of a node in a binary tree is the length of the path from the root node to that particular node. The depth of the root node is 0.
Tree traversal in a binary tree can be done in different ways: In-order traversal, Pre-order traversal, Post-order traversal, and Level-order traversal (also known as breadth-first traversal).
6. What is an Inorder traversal in Binary Tree?
In Inorder traversal, nodes are recursively visited in this order: left child, root, right child. This traversal results in nodes being visited in non-decreasing order in a binary search tree.
7. What is a Preorder traversal in Binary Tree?
In Preorder traversal, nodes are recursively visited in this order: root, left child, right child. This traversal results in root node being the first node to be visited.
8. What is a Postorder traversal in Binary Tree?
In Postorder traversal, nodes are recursively visited in this order: left child, right child and root. This traversal results in root node being the last node to be visited.
9. What is the difference between a Binary Tree and a Binary Search Tree?
A binary tree is a hierarchical data structure where each node has at most two children, whereas a binary search tree is a type of binary tree in which the left child of a node contains values less than the node’s value, and the right child contains values greater than the node’s value.
10. What is a balanced binary tree?
A balanced binary tree is a binary tree in which the height of the left and right subtrees of every node differ by at most one. Balanced trees help maintain efficient operations such as searching, insertion, and deletion with time complexities close to O(log n).
Conclusion:
Tree is a hierarchical data structure. Main uses of trees include maintaining hierarchical data, providing moderate access and insert/delete operations. Binary trees are special cases of tree where every node has at most two children.
Related Articles:
Similar Reads
Binary Tree Data Structure
A Binary Tree Data Structure is a hierarchical data structure in which each node has at most two children, referred to as the left child and the right child. It is commonly used in computer science for efficient storage and retrieval of data, with various operations such as insertion, deletion, and
3 min read
Introduction to Binary Tree
Binary Tree is a non-linear and hierarchical data structure where each node has at most two children referred to as the left child and the right child. The topmost node in a binary tree is called the root, and the bottom-most nodes are called leaves. Representation of Binary TreeEach node in a Binar
15+ min read
Properties of Binary Tree
In this post, the properties of a binary tree are discussed: 1. The maximum number of nodes at level 'l' of a binary tree is 2l: Note: Here level is the number of nodes on the path from the root to the node (including root and node). The level of the root is 0 This can be proved by induction: For ro
6 min read
Applications, Advantages and Disadvantages of Binary Tree
A binary tree is a tree that has at most two children for any of its nodes. There are several types of binary trees. To learn more about them please refer to the article on "Types of binary tree" Real-time applications of Binary Trees DOM in HTML.File explorerEvaluate an expressionRouting Algorithms
2 min read
Binary Tree (Array implementation)
Given an array that represents a tree in such a way that array indexes are values in tree nodes and array values give the parent node of that particular index (or node). The value of the root node index would always be -1 as there is no parent for root. Construct the standard linked representation o
6 min read
Maximum Depth or Height of Binary Tree
Given a binary tree, the task is to find the maximum height of the tree. The height of the tree is the number of edges in the tree from the root to the deepest node. Examples: Example 1: The height of the below binary tree is 2. Example 2: The height of the below binary tree is 3 Table of Content [E
15+ min read
Insertion in a Binary Tree in level order
Given a binary tree and a key, the task is to insert the key into the binary tree at the first position available in level order manner. Examples: Input: key = 12 Output: Explanation: Node with value 20 is inserted into the binary tree at the first position available in level order manner. Approach:
8 min read
Deletion in a Binary Tree
Given a binary tree, the task is to delete a given node from it by making sure that the tree shrinks from the bottom (i.e. the deleted node is replaced by the bottom-most and rightmost node). This is different from BST deletion. Here we do not have any order among elements, so we replace them with t
12 min read
Enumeration of Binary Trees
A Binary Tree is labeled if every node is assigned a label and a Binary Tree is unlabelled if nodes are not assigned any label. Below two are considered same unlabelled trees o o / \ / \ o o o o Below two are considered different labelled trees A C / \ / \ B C A B How many different Unlabelled Binar
3 min read
Some important Binary tree traversals
Level Order Traversal (Breadth First Search or BFS) of Binary Tree
Level Order Traversal technique is a method to traverse a Tree such that all nodes present in the same level are traversed completely before traversing the next level. Example: Input: Output: [[1], [3, 2], [4], [6, 5]] How does Level Order Traversal work? The main idea of level order traversal is to
12 min read
Level order traversal in spiral form
Given a Binary Tree, the task is to print the Level order traversal of the Binary Tree in spiral form i.e, alternate order. Example: Input:Output: 1 2 3 4 5 6 7Explanation: Level 1: 1Level 2: 2 3Level 3: 7 6 5 4Nodes are traversed in the alternate order from front or back in adjacent levels , so the
15+ min read
Reverse Level Order Traversal
Given a binary tree, the task is to find its reverse level order traversal. The idea is to print the last level first, then the second last level, and so on. Like Level order traversal, every level is printed from left to right. Examples: Input: Output:4 52 31 Table of Content [Naive Approach] Using
15+ min read
BFS vs DFS for Binary Tree
Breadth-First Search (BFS) and Depth-First Search (DFS) for Binary Trees are ways to traverse nodes of the Binary Tree. This article aims to provide the basic difference between BFS and DFS for Binary Tree. A Tree is typically traversed in two ways:Breadth First Traversal (Or Level Order Traversal)D
3 min read
Morris traversal for Preorder
Given a Binary Tree, the task is to print its Preorder Traversal, without using recursion or stack. Examples: Input: Output: 1 2 4 5 3Explanation: Preorder traversal (Root->Left->Right) of the tree is 1 2 4 5 3 Input: Output: 8 1 7 10 5 10 6 6Explanation: Preorder traversal (Root->Left->
9 min read
Iterative Preorder Traversal
Given a Binary Tree, write an iterative function to print the Preorder traversal of the given binary tree.Refer to this for recursive preorder traversal of Binary Tree. To convert an inherently recursive procedure to iterative, we need an explicit stack. Following is a simple stack based iterative p
15+ min read
Iterative Postorder Traversal | Set 1 (Using Two Stacks)
Given a binary tree, the task is to find the postorder traversal of the tree without using recursion.Examples: Input: Output: 4 5 2 3 1Explanation: Postorder traversal (Left->Right->Root) of the tree is 4 5 2 3 1. Input: Output: 10 7 1 6 10 6 5 8 Explanation: Postorder traversal (Left->Righ
10 min read
Diagonal Traversal of Binary Tree
Given a Binary Tree, the task is to print the diagonal traversal of the binary tree.Note: If the diagonal element are present in two different subtrees, then left subtree diagonal element should be taken first and then right subtree. Example: Input: Output: 8 10 14 3 6 7 13 1 4Explanation: The above
7 min read
Boundary Traversal of binary tree
Given a binary tree, the task is to find the boundary nodes of the binary tree Anti-Clockwise starting from the root. The boundary includes: left boundary (nodes on left excluding leaf nodes)leaves (consist of only the leaf nodes)right boundary (nodes on right excluding leaf nodes)The left boundary
15+ min read
Easy problems on Binary Tree
Calculate depth of a full Binary tree from Preorder
Given the preorder sequence of a full binary tree, calculate its depth(or height) [starting from depth 0]. The preorder is given as a string with two possible characters. 'l' denotes the leaf node'n' denotes internal nodeThe given tree can be seen as a full binary tree where every node has 0 or two
5 min read
Construct a tree from Inorder and Level order traversals | Set 1
Given in-order and level-order traversals of a Binary Tree, the task is to construct the Binary Tree and return its root. Example: Input:in[] = {4, 8, 10, 12, 14, 20, 22};level[] = {20, 8, 22, 4, 12, 10, 14};Output: Approach: The idea is to construct the root node from the first element of the level
9 min read
Check if a given Binary Tree is Sum Tree
Given a binary tree, the task is to check if it is a Sum Tree. A Sum Tree is a Binary Tree where the value of a node is equal to the sum of the nodes present in its left subtree and right subtree. An empty tree is Sum Tree and the sum of an empty tree can be considered as 0. A leaf node is also cons
15+ min read
Check if two nodes are cousins in a Binary Tree
Given a binary tree (having distinct node values) root and two node values. The task is to check whether the two nodes with values a and b are cousins.Note: Two nodes of a binary tree are cousins if they have the same depth with different parents. Example: Input: a = 5, b = 4 Output: TrueExplanation
13 min read
Check if removing an edge can divide a Binary Tree in two halves
Given a Binary Tree, the task is to find if there exists an edge whose removal creates two trees of equal size. Examples: Input: Output : TrueExplanation: Removing edge 5-6 creates two trees of equal size. Input: Output : FalseExplanation: There is no edge whose removal creates two trees of equal si
15+ min read
Check whether a given binary tree is perfect or not
Given a Binary Tree, the task is to check whether the given Binary Tree is a perfect Binary Tree or not.Note: A Binary tree is a Perfect Binary Tree in which all internal nodes have two children and all leaves are at the same level.A Perfect Binary Tree of height h has 2h – 1 nodes.Examples: Input:
14 min read
Check if a Binary Tree contains duplicate subtrees of size 2 or more
Given a Binary Tree, the task is to check whether the Binary tree contains a duplicate sub-tree of size 2 or more. Note: Two same leaf nodes are not considered as the subtree as the size of a leaf node is one. Example: Input: Output: TrueExplanation: Table of Content [Naive Approach] Generating All
15 min read
Check if two trees are Mirror
Given two Binary Trees, the task is to check if two trees are mirror of each other or not. For two trees ‘a’ and ‘b’ to be mirror images, the following three conditions must be true: Their root node’s key must be sameLeft subtree of root of ‘a’ and right subtree root of ‘b’ are mirror.Right subtree
9 min read
Foldable Binary Trees
Given a binary tree, the task is to find out if the tree can be folded or not. A tree can be folded if the left and right subtrees of the tree are structure-wise mirror images of each other. An empty tree is considered foldable. Examples: Input: Output: TrueExplanation: The above tree can be folded
15+ min read
Symmetric Tree (Mirror Image of itself)
Given a binary tree, the task is to check whether it is a mirror of itself. Example: Input: Output: TrueExplanation: As the left and right half of the above tree is mirror image, tree is symmetric. Input: Output: FalseExplanation: As the left and right half of the above tree is not the mirror image,
15+ min read
Program to Determine if given Two Trees are Identical or not
Given two binary trees, the task is to find if both of them are identical or not. Two trees are identical when they have the same data and the arrangement of data is also the same. Examples: Input: Output: YesExplanation: Trees are identical. Input: Output: NoExplanation: Trees are not identical. Ta
15+ min read
Subtree with given sum in a Binary Tree
You are given a binary tree and a given sum. The task is to check if there exists a subtree whose sum of all nodes is equal to the given sum. Examples: Input : key = 11 Output: TrueExplanation: sum of all nodes of subtree {2, 4, 5} = 11.Input : key = 6 Output: FalseExplanation: No subtree whose sum
15 min read
Succinct Encoding of Binary Tree
A succinct encoding of Binary Tree takes close to the minimum possible space. The number of structurally different binary trees on n nodes is n'th Catalan number. For large n, this is about 4n; thus we need at least about log2 4n = 2n bits to encode it. A succinct binary tree therefore would occupy
10 min read
Write a program to Calculate Size of a tree | Recursion
Given a binary tree, the task is to find the size of the tree. The size of a tree is the number of nodes present in the tree. Examples: Input: Output: 6Explanation: The number of nodes in the above binary tree is 6. Approach: The idea is to recursively calculate the size of tree. For each node (star
5 min read
Diameter of a Binary Tree
Given a binary tree, the task is to determine the diameter of the tree. The diameter/width of a tree is defined as the number of edges on the longest path between any two nodes. Examples: Input: Output: 2Explanation: The longest path has 2 edges (node 2 -> node 1 -> node 3). Input: Output: 4Ex
15+ min read
Level of a Node in Binary Tree
Given a Binary Tree and a key, the task is to find the level of key in the Binary Tree. Examples: Input : key = 4 Output: 3Explanation: The level of the key in above binary tree is 3.Input : key = 10 Output: -1Explanation: Key is not present in the above Binary tree. Table of Content [Expected Appro
12 min read
Intermediate problems on Binary Tree
Find all possible Binary Trees with given Inorder Traversal
Given an array that represents Inorder Traversal, the task is to find all possible Binary Trees with the given inorder traversal and print their preorder traversals. Examples: Input: inorder[] = {7, 5}Output: 5 77 5 Input: inorder[] = {1, 2, 3}Output: 1 2 31 3 22 1 33 1 23 2 1 Approach: The idea is
8 min read
Populate Inorder Successor for all nodes
Given a Binary Tree where each node has the following structure, write a function to populate the next pointer for all nodes. The next pointer for every node should be set to point to in-order successor. C/C++ Code class node { public: int data; node* left; node* right; node* next; }; // This code i
8 min read
Construct Complete Binary Tree from its Linked List Representation
Given the Linked List Representation of a Complete Binary Tree, the task is to construct the complete binary tree. The complete binary tree is represented as a linked list in a way where if the root node is stored at position i, its left, and right children are stored at position 2*i+1, and 2*i+2 re
10 min read
Minimum swap required to convert binary tree to binary search tree
Given an array arr[] which represents a Complete Binary Tree i.e., if index i is the parent, index 2*i + 1 is the left child and index 2*i + 2 is the right child. The task is to find the minimum number of swaps required to convert it into a Binary Search Tree. Examples: Input: arr[] = [5, 6, 7, 8, 9
9 min read
Convert Binary Tree to Doubly Linked List using inorder traversal
Given a Binary Tree (BT), the task is to convert it to a Doubly Linked List (DLL) in place. The left and right pointers in nodes will be used as previous and next pointers respectively in converted DLL. The order of nodes in DLL must be the same as the order of the given Binary Tree. The first node
15+ min read
Convert a tree to forest of even nodes
Given a tree of n even nodes. The task is to find the maximum number of edges to be removed from the given tree to obtain a forest of trees having an even number of nodes. This problem is always solvable as the given graph has even nodes. Examples: Input: Output: 2Explanation: By removing 2 edges sh
8 min read
Flip Binary Tree
Given a binary tree, the task is to flip the binary tree towards the right direction that is clockwise. Input: Output: Explanation: In the flip operation, the leftmost node becomes the root of the flipped tree and its parent becomes its right child and the right sibling becomes its left child and th
14 min read
Print root to leaf paths without using recursion
Given a Binary Tree of nodes, the task is to find all the possible paths from the root node to all the leaf nodes of the binary tree. Example: Input: Output: 1 2 41 2 51 3 Table of Content [Expected Approach - 1] Using Parent HashMap - O(n) Time and O(n) Space[Expected Approach - 2] Using Stack - O(
15+ min read
Check if given Preorder, Inorder and Postorder traversals are of same tree
Given the Preorder, Inorder, and Postorder traversals of some trees, the task is to check if they all belong to the same tree. Examples: Input: inOrder[] = [4, 2, 5, 1, 3] preOrder[] = [1, 2, 4, 5, 3] postOrder = [4, 5, 2, 3, 1] Output: TrueExplanation: All of the above three traversals are of the s
15+ min read
Check whether a given Binary Tree is Complete or not (Iterative Solution)
Given a Binary Tree, the task is to check whether the given Binary Tree is a Complete Binary Tree or not.A complete binary tree is a binary tree in which every level, except possibly the last, is completely filled, and all nodes are as far left as possible. Examples: The following trees are examples
12 min read
Check if a binary tree is subtree of another binary tree | Set 2
Given two binary trees, check if the first tree is a subtree of the second one. A subtree of a tree T is a tree S consisting of a node in T and all of its descendants in T. The subtree corresponding to the root node is the entire tree; the subtree corresponding to any other node is called a proper s
15+ min read
Find largest subtree sum in a tree
Given a Binary Tree, the task is to find a subtree with the maximum sum in the tree. Examples: Input: Output: 28Explanation: As all the tree elements are positive, the largest subtree sum is equal to sum of all tree elements. Input: Output: 7Explanation: Subtree with largest sum is: Table of Content
15+ min read
Maximum sum of nodes in Binary tree such that no two are adjacent
Given a binary tree with a value associated with each node, we need to choose a subset of these nodes such that the sum of selected nodes is maximum under a constraint that no two chosen nodes in the subset should be directly connected, that is, if we have taken a node in our sum then we can’t take
15+ min read
Lowest Common Ancestor in a Binary Tree
Given the root of a Binary Tree with all unique values and two node values n1 and n2, the task is to find the lowest common ancestor of the given two nodes. The Lowest Common Ancestor (or LCA) is the lowest node in the tree that has both n1 and n2 as descendants. In other words, the LCA of n1 and n2
15+ min read
Height of a generic tree from parent array
Given a tree of size n as array parent[0..n-1] where every index i in the parent[] represents a node and the value at i represents the immediate parent of that node. For root, the node value will be -1. Find the height of the generic tree given the parent links. Examples: Input: parent[] = [-1, 0, 0
13 min read
Find distance between two nodes of a Binary Tree
Given a Binary tree, the task is to find the distance between two keys in a binary tree, no parent pointers are given. The distance between two nodes is the minimum number of edges to be traversed to reach one node from another. The given two nodes are guaranteed to be in the binary tree and all nod
15+ min read
Hard problems on Binary Tree
Modify a binary tree to get preorder traversal using right pointers only
Given a binary tree. The task is to modify it in such a way that after modification preorder traversal of it can get only with the right pointers. During modification, we can use right as well as left pointers. Examples: Input : Output : Explanation: The preorder traversal of given binary tree is 10
12 min read
Construct Full Binary Tree using its Preorder traversal and Preorder traversal of its mirror tree
Given two arrays that represent Preorder traversals of a full binary tree and its mirror tree, the task is to construct the binary tree using these two Preorder traversals. A Full Binary Tree is a binary tree where every node has either 0 or 2 children. Note: It is not possible to construct a genera
9 min read
Construct a special tree from given preorder traversal
Given an array pre[] that represents the Preorder traversal of a special binary tree where every node has either 0 or 2 children. One more array preLN[] is given which has only two possible values ‘L’ and ‘N’. The value ‘L’ in preLN[] indicates that the corresponding node in Binary Tree is a leaf no
12 min read
Construct tree from ancestor matrix
Given an ancestor matrix mat[n][n] where the Ancestor matrix is defined as below. mat[i][j] = 1 if i is ancestor of jmat[i][j] = 0, otherwiseConstruct a Binary Tree from a given ancestor matrix where all its values of nodes are from 0 to n-1. It may be assumed that the input provided in the program
11 min read
Construct the full k-ary tree from its preorder traversal
Given an array that contains the preorder traversal of the full k-ary tree, the task is to construct the full k-ary tree and return its postorder traversal. A full k-ary tree is a tree where each node has either 0 or k children. Examples: Input: preorder[] = {1, 2, 5, 6, 7, 3, 8, 9, 10, 4}, k = 3 Ou
6 min read
Construct Binary Tree from String with bracket representation
Construct a binary tree from a string consisting of parenthesis and integers. The whole input represents a binary tree. It contains an integer followed by zero, one or two pairs of parenthesis. The integer represents the root's value and a pair of parenthesis contains a child binary tree with the sa
15+ min read
Convert a Binary Tree into Doubly Linked List in spiral fashion
Given a binary tree, convert it into a doubly linked list (DLL) where the nodes are arranged in a spiral order. The left pointer of the binary tree node should act as the previous node in the DLL, and the right pointer should act as the next node in the DLL. The solution should not allocate extra me
10 min read
Convert a Binary Tree to a Circular Doubly Link List
Given a Binary Tree, convert it to a Circular Doubly Linked List (In-Place). The left and right pointers in nodes are to be used as previous and next pointers respectively in the converted Circular Linked List.The order of nodes in the List must be the same as in Inorder for the given Binary Tree.Th
15+ min read
Convert Ternary Expression to a Binary Tree
Given a string that contains ternary expressions. The expressions may be nested, task is convert the given ternary expression to a binary Tree. Examples: Input : string expression = a?b:c Output : a / \ b cInput : expression = a?b?c:d:eOutput : a / \ b e / \ c dAsked In : Facebook Interview Idea is
11 min read
Check if there is a root to leaf path with given sequence
Given a binary tree and an array, the task is to find if the given array sequence is present as a root-to-leaf path in given tree. Examples: Input: arr = {5, 2, 4, 8} Output: TrueExplanation: The given array sequence {5, 2, 4, 8} is present as a root-to-leaf path in given tree. Input: arr = {5, 3, 4
8 min read
Remove all nodes which lie on a path having sum less than k
Given a binary tree, a complete path is defined as a path from a root to a leaf. The sum of all nodes on that path is defined as the sum of that path. Given the number k, the task is to remove all nodes that lie on a path with a sum less than k. Note: A node can be part of multiple paths. So we have
8 min read
Maximum spiral sum in Binary Tree
Given a binary tree containing n nodes. The task is to find the maximum sum obtained when the tree is spirally traversed. In spiral traversal one by one all levels are being traversed with the root level traversed from right to left, then the next level from left to right, then further next level fr
9 min read
Sum of nodes at k-th level in a tree represented as string
Given an integer k and a binary tree in string format. Every node of a tree has a value in the range of 0 to 9. The task is to find the sum of elements at the k-th level from the root. The root is at level 0. Tree is given in the form: (node value(left subtree)(right subtree)) Examples: Input : s =
11 min read
Sum of all the numbers that are formed from root to leaf paths
Given a binary tree, where every node value is a number. Find the sum of all the numbers that are formed from root to leaf paths. Examples: Input: Output: 13997Explanation: There are 4 leaves, hence 4 root to leaf paths: 6->3->2 = 6326->3->5->7 = 63576->3->5->4 = 63546->5-
13 min read
Merge Two Binary Trees by doing Node Sum
Given the roots of two binary trees. The task is to merge the two trees. The merge rule is that if two nodes overlap, then sum node values up as the new value of the merged node. Otherwise, the non-null node will be used as the node of the new tree. Note: The merging process must start from the root
15+ min read
Find the Root of a Tree from the Sum of Child Node IDs
Given a Binary Tree with nodes labelled from 1 to n, where n is the total number of nodes. The task is to identify the root of binary tree given that each node is described by a pair consisting of its id and the sum of its children's id's. Examples: Input: [[1, 5], [2, 0], [3, 0], [4, 0], [5, 5], [6
5 min read