Largest value in each level of Binary Tree
Last Updated :
22 May, 2024
Given a binary tree, find the largest value in each level.
Examples :
Input :
1
/ \
2 3
Output : 1 3
Input :
4
/ \
9 2
/ \ \
3 5 7
Output : 4 9 7
Approach: The idea is to recursively traverse tree in a pre-order fashion. Root is considered to be at zeroth level. While traversing, keep track of the level of the element and if its current level is not equal to the number of elements present in the list, update the maximum element at that level in the list.
Below is the implementation to find largest value on each level of Binary Tree.
Implementation:
C++
// C++ program to find largest
// value on each level of binary tree.
#include <bits/stdc++.h>
using namespace std;
/* A binary tree node has data,
pointer to left child and a
pointer to right child */
struct Node {
int val;
struct Node *left, *right;
};
/* Recursive function to find
the largest value on each level */
void helper(vector<int>& res, Node* root, int d)
{
if (!root)
return;
// Expand list size
if (d == res.size())
res.push_back(root->val);
else
// to ensure largest value
// on level is being stored
res[d] = max(res[d], root->val);
// Recursively traverse left and
// right subtrees in order to find
// out the largest value on each level
helper(res, root->left, d + 1);
helper(res, root->right, d + 1);
}
// function to find largest values
vector<int> largestValues(Node* root)
{
vector<int> res;
helper(res, root, 0);
return res;
}
/* Helper function that allocates a
new node with the given data and
NULL left and right pointers. */
Node* newNode(int data)
{
Node* temp = new Node;
temp->val = data;
temp->left = temp->right = NULL;
return temp;
}
// Driver code
int main()
{
/* Let us construct a Binary Tree
4
/ \
9 2
/ \ \
3 5 7 */
Node* root = NULL;
root = newNode(4);
root->left = newNode(9);
root->right = newNode(2);
root->left->left = newNode(3);
root->left->right = newNode(5);
root->right->right = newNode(7);
vector<int> res = largestValues(root);
for (int i = 0; i < res.size(); i++)
cout << res[i] << " ";
return 0;
}
Java
// Java program to find largest
// value on each level of binary tree.
import java.util.*;
public class GFG
{
/* A binary tree node has data,
pointer to left child and a
pointer to right child */
static class Node
{
int val;
Node left, right;
};
/* Recursive function to find
the largest value on each level */
static void helper(Vector<Integer> res, Node root, int d)
{
if (root == null)
return;
// Expand list size
if (d == res.size())
res.add(root.val);
else
// to ensure largest value
// on level is being stored
res.set(d, Math.max(res.get(d), root.val));
// Recursively traverse left and
// right subtrees in order to find
// out the largest value on each level
helper(res, root.left, d + 1);
helper(res, root.right, d + 1);
}
// function to find largest values
static Vector<Integer> largestValues(Node root)
{
Vector<Integer> res = new Vector<>();
helper(res, root, 0);
return res;
}
/* Helper function that allocates a
new node with the given data and
NULL left and right pointers. */
static Node newNode(int data)
{
Node temp = new Node();
temp.val = data;
temp.left = temp.right = null;
return temp;
}
// Driver code
public static void main(String[] args)
{
/* Let us construct a Binary Tree
4
/ \
9 2
/ \ \
3 5 7 */
Node root = null;
root = newNode(4);
root.left = newNode(9);
root.right = newNode(2);
root.left.left = newNode(3);
root.left.right = newNode(5);
root.right.right = newNode(7);
Vector<Integer> res = largestValues(root);
for (int i = 0; i < res.size(); i++)
System.out.print(res.get(i)+" ");
}
}
/* This code is contributed by PrinciRaj1992 */
Python
# Python program to find largest value
# on each level of binary tree.
""" Recursive function to find
the largest value on each level """
def helper(res, root, d):
if ( not root):
return
# Expand list size
if (d == len(res)):
res.append(root.val)
else:
# to ensure largest value
# on level is being stored
res[d] = max(res[d], root.val)
# Recursively traverse left and
# right subtrees in order to find
# out the largest value on each level
helper(res, root.left, d + 1)
helper(res, root.right, d + 1)
# function to find largest values
def largestValues(root):
res = []
helper(res, root, 0)
return res
# Helper function that allocates a new
# node with the given data and None left
# and right pointers.
class newNode:
# Constructor to create a new node
def __init__(self, data):
self.val = data
self.left = None
self.right = None
# Driver Code
if __name__ == '__main__':
""" Let us construct the following Tree
4
/ \
9 2
/ \ \
3 5 7 """
root = newNode(4)
root.left = newNode(9)
root.right = newNode(2)
root.left.left = newNode(3)
root.left.right = newNode(5)
root.right.right = newNode(7)
print(*largestValues(root))
# This code is contributed
# Shubham Singh(SHUBHAMSINGH10)
C#
// C# program to find largest
// value on each level of binary tree.
using System;
using System.Collections.Generic;
class GFG
{
/* A binary tree node has data,
pointer to left child and a
pointer to right child */
public class Node
{
public int val;
public Node left, right;
};
/* Recursive function to find
the largest value on each level */
static void helper(List<int> res,
Node root, int d)
{
if (root == null)
return;
// Expand list size
if (d == res.Count)
res.Add(root.val);
else
// to ensure largest value
// on level is being stored
res[d] = Math.Max(res[d], root.val);
// Recursively traverse left and
// right subtrees in order to find
// out the largest value on each level
helper(res, root.left, d + 1);
helper(res, root.right, d + 1);
}
// function to find largest values
static List<int> largestValues(Node root)
{
List<int> res = new List<int>();
helper(res, root, 0);
return res;
}
/* Helper function that allocates a
new node with the given data and
NULL left and right pointers. */
static Node newNode(int data)
{
Node temp = new Node();
temp.val = data;
temp.left = temp.right = null;
return temp;
}
// Driver code
public static void Main(String[] args)
{
/* Let us construct a Binary Tree
4
/ \
9 2
/ \ \
3 5 7 */
Node root = null;
root = newNode(4);
root.left = newNode(9);
root.right = newNode(2);
root.left.left = newNode(3);
root.left.right = newNode(5);
root.right.right = newNode(7);
List<int> res = largestValues(root);
for (int i = 0; i < res.Count; i++)
Console.Write(res[i] + " ");
}
}
// This code is contributed by 29AjayKumar
JavaScript
// JavaScript program to find largest
// value on each level of binary tree.
/* A binary tree node has data,
pointer to left child and a
pointer to right child */
class Node
{
constructor(data) {
this.left = null;
this.right = null;
this.val = data;
}
}
/* Recursive function to find
the largest value on each level */
function helper(res, root, d)
{
if (root == null)
return;
// Expand list size
if (d == res.length)
res.push(root.val);
else
// to ensure largest value
// on level is being stored
res[d] = Math.max(res[d], root.val);
// Recursively traverse left and
// right subtrees in order to find
// out the largest value on each level
helper(res, root.left, d + 1);
helper(res, root.right, d + 1);
}
// function to find largest values
function largestValues(root)
{
let res = [];
helper(res, root, 0);
return res;
}
/* Helper function that allocates a
new node with the given data and
NULL left and right pointers. */
function newNode(data)
{
let temp = new Node(data);
return temp;
}
/* Let us construct a Binary Tree
4
/ \
9 2
/ \ \
3 5 7 */
let root = null;
root = newNode(4);
root.left = newNode(9);
root.right = newNode(2);
root.left.left = newNode(3);
root.left.right = newNode(5);
root.right.right = newNode(7);
let res = largestValues(root);
for (let i = 0; i < res.length; i++)
console.log(res[i]+" ");
Largest value in each level of Binary Tree | Set-2 (Iterative Approach)
Complexity Analysis:
- Time complexity: O(n), where n is the number of nodes in binary tree.
- Auxiliary Space: O(n) as in worst case, depth of binary tree will be n.
Another Approach:
The above approach for finding the largest value on each level of a binary tree is based on the level-order traversal technique.
Intuition:
The approach first creates an empty queue and pushes the root node into it. Then it enters into a while loop that will run until the queue is not empty. Inside the while loop, it first calculates the current size of the queue, which represents the number of nodes present at the current level. Then it loops through all the nodes at the current level and pushes their child nodes (if any) into the queue. While doing this, it also checks if the current node's value is greater than the current maximum value for that level. If it is greater, then it updates the maximum value for that level.
After the loop, it adds the current maximum value to the result vector. Once all the levels are traversed, the result vector containing the largest value on each level is returned.
This approach has a time complexity of O(N), where N is the number of nodes in the binary tree, as it traverses each node only once. The space complexity of this approach is also O(N), as the maximum number of nodes that can be present in the queue at any given time is N/2 (the number of nodes in the last level of a complete binary tree).
Here are the implementation:
C++
#include <bits/stdc++.h>
using namespace std;
/* A binary tree node has data,
pointer to left child and a
pointer to right child */
struct Node {
int val;
struct Node *left, *right;
};
/* Function to find largest value
on each level of binary tree */
vector<int> largestValues(Node* root) {
vector<int> res;
if (!root) return res;
queue<Node*> q;
q.push(root);
while (!q.empty()) {
int n = q.size();
int maxVal = INT_MIN;
for (int i = 0; i < n; i++) {
Node* node = q.front();
q.pop();
maxVal = max(maxVal, node->val);
if (node->left) q.push(node->left);
if (node->right) q.push(node->right);
}
res.push_back(maxVal);
}
return res;
}
/* Helper function that allocates a
new node with the given data and
NULL left and right pointers. */
Node* newNode(int data)
{
Node* temp = new Node;
temp->val = data;
temp->left = temp->right = NULL;
return temp;
}
// Driver code
int main()
{
/* Let us construct a Binary Tree
4
/ \
9 2
/ \ \
3 5 7 */
Node* root = NULL;
root = newNode(4);
root->left = newNode(9);
root->right = newNode(2);
root->left->left = newNode(3);
root->left->right = newNode(5);
root->right->right = newNode(7);
vector<int> res = largestValues(root);
for (int i = 0; i < res.size(); i++)
cout << res[i] << " ";
return 0;
}
Java
import java.util.*;
// A binary tree node has data,
// pointer to left child, and a
// pointer to the right child
class Node {
int val;
Node left, right;
Node(int data)
{
val = data;
left = right = null;
}
}
public class GFG {
// Function to find largest value on each level of
// binary tree
static List<Integer> largestValues(Node root)
{
List<Integer> res = new ArrayList<>();
if (root == null)
return res;
Queue<Node> q = new LinkedList<>();
q.add(root);
while (!q.isEmpty()) {
int n = q.size();
int maxVal = Integer.MIN_VALUE;
for (int i = 0; i < n; i++) {
Node node = q.poll();
maxVal = Math.max(maxVal, node.val);
if (node.left != null)
q.add(node.left);
if (node.right != null)
q.add(node.right);
}
res.add(maxVal);
}
return res;
}
// Driver code
public static void main(String[] args)
{
/* Let us construct a Binary Tree
4
/ \
9 2
/ \ \
3 5 7 */
Node root = new Node(4);
root.left = new Node(9);
root.right = new Node(2);
root.left.left = new Node(3);
root.left.right = new Node(5);
root.right.right = new Node(7);
List<Integer> res = largestValues(root);
for (int i = 0; i < res.size(); i++)
System.out.print(res.get(i) + " ");
}
}
Python
from collections import deque
# A binary tree node has data, pointer to left child,
# and a pointer to right child
class Node:
def __init__(self, val=0, left=None, right=None):
self.val = val
self.left = left
self.right = right
# Function to find the largest value on each level of a binary tree
def largestValues(root):
res = []
if not root:
return res
q = deque()
q.append(root)
while q:
n = len(q)
maxVal = float('-inf')
for i in range(n):
node = q.popleft()
maxVal = max(maxVal, node.val)
if node.left:
q.append(node.left)
if node.right:
q.append(node.right)
res.append(maxVal)
return res
# Helper function that allocates a new node with the given data and NULL left and right pointers
def newNode(data):
temp = Node()
temp.val = data
temp.left = temp.right = None
return temp
# Driver code
if __name__ == "__main__":
# Let us construct a Binary Tree
# 4
# / \
# 9 2
# / \ \
# 3 5 7
root = newNode(4)
root.left = newNode(9)
root.right = newNode(2)
root.left.left = newNode(3)
root.left.right = newNode(5)
root.right.right = newNode(7)
res = largestValues(root)
for val in res:
print(val),
C#
using System;
using System.Collections.Generic;
/* A binary tree node has data,
pointer to left child and a
pointer to right child */
class Node {
public int val;
public Node left, right;
public Node(int item)
{
val = item;
left = right = null;
}
}
class GFG {
// Function to find the largest values in each level of
// a binary tree
static List<int> LargestValues(Node root)
{
List<int> res
= new List<int>(); // Initialize a list to store
// the largest values
if (root == null)
return res; // Return an empty list if the tree
// is empty
Queue<Node> q
= new Queue<Node>(); // Create a queue to
// perform a level-order
// traversal
q.Enqueue(root); // Enqueue the root node as the
// starting point
// Perform a level-order traversal of the binary
// tree
while (q.Count > 0) {
int n = q.Count; // Get the number of nodes at
// the current level
int maxVal = int.MinValue; // Initialize the
// maximum value for
// the current level
// Traverse all the nodes at the current level
for (int i = 0; i < n; i++) {
Node node
= q.Dequeue(); // Dequeue the front node
maxVal = Math.Max(
maxVal,
node.val); // Update the maximum value
// for the current level
// Enqueue the left and right child nodes of
// the current node if they exist
if (node.left != null)
q.Enqueue(node.left);
if (node.right != null)
q.Enqueue(node.right);
}
// After traversing all nodes at the current
// level, add the maximum value to the result
// list
res.Add(maxVal);
}
return res; // Return the list containing the
// largest values at each level of the
// binary tree
}
static void Main()
{
// Construct the binary tree
Node root = new Node(4);
root.left = new Node(9);
root.right = new Node(2);
root.left.left = new Node(3);
root.left.right = new Node(5);
root.right.right = new Node(7);
// Find the largest values at each level and print
// the results
List<int> res = LargestValues(root);
for (int i = 0; i < res.Count; i++)
Console.Write(res[i] + " ");
}
}
JavaScript
// Definition of a binary tree node
class TreeNode {
constructor(val) {
this.val = val;
this.left = null;
this.right = null;
}
}
// Function to find the largest value on each level of a binary tree
function largestValues(root) {
const res = [];
if (!root) return res;
const queue = [];
queue.push(root);
while (queue.length > 0) {
const n = queue.length;
let maxVal = Number.MIN_SAFE_INTEGER;
for (let i = 0; i < n; i++) {
const node = queue.shift();
maxVal = Math.max(maxVal, node.val);
if (node.left) queue.push(node.left);
if (node.right) queue.push(node.right);
}
res.push(maxVal);
}
return res;
}
// Helper function to construct a new tree node
function newNode(data) {
const temp = new TreeNode(data);
return temp;
}
// Driver code
function main() {
// Construct the binary tree:
// 4
// / \
// 9 2
// / \ \
// 3 5 7
const root = newNode(4);
root.left = newNode(9);
root.right = newNode(2);
root.left.left = newNode(3);
root.left.right = newNode(5);
root.right.right = newNode(7);
const res = largestValues(root);
console.log("Largest values on each level:");
for (let i = 0; i < res.length; i++) {
console.log(res[i]);
}
}
// Call the main function to start the program
main();
Time complexity: O(N)
Auxiliary Space: O(W)
The time complexity of the above approach is O(N), where N is the number of nodes in the binary tree. This is because the algorithm visits each node once, and each operation performed on a node takes constant time.
The space complexity of the algorithm is O(W), where W is the maximum width of the binary tree. In the worst case, the algorithm will have to store all the nodes in the last level of the binary tree in the queue before processing them. The maximum number of nodes that can be present in the last level of a binary tree is (N+1)/2, where N is the total number of nodes in the tree. Therefore, the space complexity of the algorithm is O((N+1)/2), which simplifies to O(N) in the worst case.
Approach: Using BFS
This program using a Breadth-First Search (BFS) approach finds the largest value on each level of a binary tree. Here's the intuition behind the algorithm:
- We start by initializing an empty vector res to store the largest values on each level of the tree.
- We perform a BFS traversal of the binary tree using a queue. We start by pushing the root node into the queue.
- While the queue is not empty, we process each level of the tree: a. Get the current size of the queue. This represents the number of nodes at the current level. b. Initialize a variable levelMax to store the maximum value at the current level. Set it to the minimum possible integer value (INT_MIN). c. Iterate through all the nodes at the current level. Remove each node from the queue and update levelMax if the value of the current node is greater than levelMax. d. Enqueue the left and right child nodes of the current node (if they exist) to continue the BFS traversal of the next level. e. Once we process all the nodes at the current level, we have the maximum value for that level. Append levelMax to the res vector.
- After the BFS traversal is complete, the res vector will contain the largest value on each level of the binary tree.
- Finally, we return the res vector.
C++
#include <bits/stdc++.h>
using namespace std;
/* A binary tree node has data,
pointer to left child and a
pointer to right child */
struct Node {
int val;
struct Node *left, *right;
};
// function to find largest values
vector<int> largestValues(Node* root)
{
vector<int> res;
if (!root)
return res;
queue<Node*> q;
q.push(root);
while (!q.empty()) {
int size = q.size();
int levelMax = INT_MIN;
for (int i = 0; i < size; i++) {
Node* current = q.front();
q.pop();
levelMax = max(levelMax, current->val);
if (current->left)
q.push(current->left);
if (current->right)
q.push(current->right);
}
res.push_back(levelMax);
}
return res;
}
/* Helper function that allocates a
new node with the given data and
NULL left and right pointers. */
Node* newNode(int data)
{
Node* temp = new Node;
temp->val = data;
temp->left = temp->right = NULL;
return temp;
}
// Driver code
int main()
{
/* Let us construct a Binary Tree
4
/ \
9 2
/ \ \
3 5 7 */
Node* root = NULL;
root = newNode(4);
root->left = newNode(9);
root->right = newNode(2);
root->left->left = newNode(3);
root->left->right = newNode(5);
root->right->right = newNode(7);
vector<int> res = largestValues(root);
for (int i = 0; i < res.size(); i++)
cout << res[i] << " ";
return 0;
}
Java
import java.util.ArrayList;
import java.util.LinkedList;
import java.util.List;
import java.util.Queue;
class TreeNode {
int val;
TreeNode left;
TreeNode right;
TreeNode(int val) {
this.val = val;
}
}
public class Main {
// Function to find the largest values in each level of a binary tree
public static List<Integer> largestValues(TreeNode root) {
List<Integer> result = new ArrayList<>();
if (root == null)
return result;
Queue<TreeNode> queue = new LinkedList<>();
queue.offer(root);
while (!queue.isEmpty()) {
int levelSize = queue.size();
int levelMax = Integer.MIN_VALUE;
// Iterate through nodes at the current level
for (int i = 0; i < levelSize; i++) {
TreeNode current = queue.poll();
levelMax = Math.max(levelMax, current.val);
// Add child nodes to the queue if they exist
if (current.left != null)
queue.offer(current.left);
if (current.right != null)
queue.offer(current.right);
}
// Add the maximum value of the current level to the result list
result.add(levelMax);
}
return result;
}
public static void main(String[] args) {
TreeNode root = new TreeNode(4);
root.left = new TreeNode(9);
root.right = new TreeNode(2);
root.left.left = new TreeNode(3);
root.left.right = new TreeNode(5);
root.right.right = new TreeNode(7);
// Find the largest values in each level of the binary tree
List<Integer> result = largestValues(root);
// Print the result
for (int value : result)
System.out.print(value + " ");
}
}
Python
from collections import deque
class TreeNode:
def __init__(self, val=0, left=None, right=None):
self.val = val
self.left = left
self.right = right
def largestValues(root):
if not root:
return []
result = [] # Initialize a list to store the largest values on each level
queue = deque() # Create a queue for BFS traversal, starting with the root node
queue.append(root)
while queue:
level_size = len(queue)
# Initialize the maximum value for the current level
level_max = float("-inf")
for _ in range(level_size):
current = queue.popleft()
level_max = max(level_max, current.val)
if current.left:
queue.append(current.left)
if current.right:
queue.append(current.right)
# Append the maximum value for the current level to the result list
result.append(level_max)
return result
# Input: Construct the binary tree
# 4
# / \
# 9 2
# / \ \
# 3 5 7
root = TreeNode(4)
root.left = TreeNode(9)
root.right = TreeNode(2)
root.left.left = TreeNode(3)
root.left.right = TreeNode(5)
root.right.right = TreeNode(7)
# Find the largest values on each level
result = largestValues(root)
print(result) # Output: [4, 9, 7]
C#
using System;
using System.Collections.Generic;
using System.Collections;
using System.Linq;
// Definition for a binary tree node
public class TreeNode {
public int val;
public TreeNode left;
public TreeNode right;
public TreeNode(int val = 0, TreeNode left = null,
TreeNode right = null)
{
this.val = val;
this.left = left;
this.right = right;
}
}
public class Solution {
public IList<int> LargestValues(TreeNode root)
{
List<int> result = new List<int>();
if (root == null)
return result;
Queue<TreeNode> queue = new Queue<TreeNode>();
queue.Enqueue(root);
while (queue.Count > 0) {
int levelMax = int.MinValue;
int levelSize = queue.Count;
for (int i = 0; i < levelSize; i++) {
TreeNode current = queue.Dequeue();
levelMax = Math.Max(levelMax, current.val);
if (current.left != null)
queue.Enqueue(current.left);
if (current.right != null)
queue.Enqueue(current.right);
}
result.Add(levelMax);
}
return result;
}
}
class Program {
static void Main(string[] args)
{
/* Let us construct a Binary Tree
4
/ \
9 2
/ \ \
3 5 7 */
TreeNode root = new TreeNode(4);
root.left = new TreeNode(9);
root.right = new TreeNode(2);
root.left.left = new TreeNode(3);
root.left.right = new TreeNode(5);
root.right.right = new TreeNode(7);
Solution solution = new Solution();
IList<int> result = solution.LargestValues(root);
Console.WriteLine("Largest values at each level:");
foreach(int val in result)
{
Console.Write(val + " ");
}
}
}
JavaScript
// Definition for a binary tree node.
class TreeNode {
constructor(val) {
this.val = val;
this.left = this.right = null;
}
}
function largestValues(root) {
const res = [];
if (!root) {
return res;
}
const queue = [root];
while (queue.length > 0) {
const size = queue.length;
let levelMax = -Infinity;
for (let i = 0; i < size; i++) {
const current = queue.shift();
levelMax = Math.max(levelMax, current.val);
if (current.left) {
queue.push(current.left);
}
if (current.right) {
queue.push(current.right);
}
}
res.push(levelMax);
}
return res;
}
// Driver code
const root = new TreeNode(4);
root.left = new TreeNode(9);
root.right = new TreeNode(2);
root.left.left = new TreeNode(3);
root.left.right = new TreeNode(5);
root.right.right = new TreeNode(7);
const res = largestValues(root);
console.log(res.join(" "));
Time complexity: O(N), where N is the number of nodes in the binary tree, as we need to visit each node once.
Auxiliary Space: O(M), where M is the maximum number of nodes at any level in the tree, as the queue can store at most M nodes at a time during the BFS traversal.
Largest value in each level of Binary Tree
Similar Reads
Basics & Prerequisites
Data Structures
Array Data StructureIn this article, we introduce array, implementation in different popular languages, its basic operations and commonly seen problems / interview questions. An array stores items (in case of C/C++ and Java Primitive Arrays) or their references (in case of Python, JS, Java Non-Primitive) at contiguous
3 min read
String in Data StructureA string is a sequence of characters. The following facts make string an interesting data structure.Small set of elements. Unlike normal array, strings typically have smaller set of items. For example, lowercase English alphabet has only 26 characters. ASCII has only 256 characters.Strings are immut
2 min read
Hashing in Data StructureHashing is a technique used in data structures that efficiently stores and retrieves data in a way that allows for quick access. Hashing involves mapping data to a specific index in a hash table (an array of items) using a hash function. It enables fast retrieval of information based on its key. The
2 min read
Linked List Data StructureA linked list is a fundamental data structure in computer science. It mainly allows efficient insertion and deletion operations compared to arrays. Like arrays, it is also used to implement other data structures like stack, queue and deque. Hereâs the comparison of Linked List vs Arrays Linked List:
2 min read
Stack Data StructureA Stack is a linear data structure that follows a particular order in which the operations are performed. The order may be LIFO(Last In First Out) or FILO(First In Last Out). LIFO implies that the element that is inserted last, comes out first and FILO implies that the element that is inserted first
2 min read
Queue Data StructureA Queue Data Structure is a fundamental concept in computer science used for storing and managing data in a specific order. It follows the principle of "First in, First out" (FIFO), where the first element added to the queue is the first one to be removed. It is used as a buffer in computer systems
2 min read
Tree Data StructureTree Data Structure is a non-linear data structure in which a collection of elements known as nodes are connected to each other via edges such that there exists exactly one path between any two nodes. Types of TreeBinary Tree : Every node has at most two childrenTernary Tree : Every node has at most
4 min read
Graph Data StructureGraph Data Structure is a collection of nodes connected by edges. It's used to represent relationships between different entities. If you are looking for topic-wise list of problems on different topics like DFS, BFS, Topological Sort, Shortest Path, etc., please refer to Graph Algorithms. Basics of
3 min read
Trie Data StructureThe Trie data structure is a tree-like structure used for storing a dynamic set of strings. It allows for efficient retrieval and storage of keys, making it highly effective in handling large datasets. Trie supports operations such as insertion, search, deletion of keys, and prefix searches. In this
15+ min read
Algorithms
Searching AlgorithmsSearching algorithms are essential tools in computer science used to locate specific items within a collection of data. In this tutorial, we are mainly going to focus upon searching in an array. When we search an item in an array, there are two most common algorithms used based on the type of input
2 min read
Sorting AlgorithmsA Sorting Algorithm is used to rearrange a given array or list of elements in an order. For example, a given array [10, 20, 5, 2] becomes [2, 5, 10, 20] after sorting in increasing order and becomes [20, 10, 5, 2] after sorting in decreasing order. There exist different sorting algorithms for differ
3 min read
Introduction to RecursionThe process in which a function calls itself directly or indirectly is called recursion and the corresponding function is called a recursive function. A recursive algorithm takes one step toward solution and then recursively call itself to further move. The algorithm stops once we reach the solution
14 min read
Greedy AlgorithmsGreedy algorithms are a class of algorithms that make locally optimal choices at each step with the hope of finding a global optimum solution. At every step of the algorithm, we make a choice that looks the best at the moment. To make the choice, we sometimes sort the array so that we can always get
3 min read
Graph AlgorithmsGraph is a non-linear data structure like tree data structure. The limitation of tree is, it can only represent hierarchical data. For situations where nodes or vertices are randomly connected with each other other, we use Graph. Example situations where we use graph data structure are, a social net
3 min read
Dynamic Programming or DPDynamic Programming is an algorithmic technique with the following properties.It is mainly an optimization over plain recursion. Wherever we see a recursive solution that has repeated calls for the same inputs, we can optimize it using Dynamic Programming. The idea is to simply store the results of
3 min read
Bitwise AlgorithmsBitwise algorithms in Data Structures and Algorithms (DSA) involve manipulating individual bits of binary representations of numbers to perform operations efficiently. These algorithms utilize bitwise operators like AND, OR, XOR, NOT, Left Shift, and Right Shift.BasicsIntroduction to Bitwise Algorit
4 min read
Advanced
Segment TreeSegment Tree is a data structure that allows efficient querying and updating of intervals or segments of an array. It is particularly useful for problems involving range queries, such as finding the sum, minimum, maximum, or any other operation over a specific range of elements in an array. The tree
3 min read
Pattern SearchingPattern searching algorithms are essential tools in computer science and data processing. These algorithms are designed to efficiently find a particular pattern within a larger set of data. Patten SearchingImportant Pattern Searching Algorithms:Naive String Matching : A Simple Algorithm that works i
2 min read
GeometryGeometry is a branch of mathematics that studies the properties, measurements, and relationships of points, lines, angles, surfaces, and solids. From basic lines and angles to complex structures, it helps us understand the world around us.Geometry for Students and BeginnersThis section covers key br
2 min read
Interview Preparation
Practice Problem