0% found this document useful (0 votes)
8 views164 pages

Ilovepdf Merged

The document provides an introduction to binary trees, describing their structure, representation, and key terminologies. It covers operations such as traversal, insertion, searching, and deletion, along with code examples in various programming languages. Additionally, it discusses the properties and types of binary trees, highlighting their hierarchical nature and the relationships between nodes.

Uploaded by

trendingtimes45
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
8 views164 pages

Ilovepdf Merged

The document provides an introduction to binary trees, describing their structure, representation, and key terminologies. It covers operations such as traversal, insertion, searching, and deletion, along with code examples in various programming languages. Additionally, it discusses the properties and types of binary trees, highlighting their hierarchical nature and the relationships between nodes.

Uploaded by

trendingtimes45
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 164

3/30/25, 4:07 PM Introduction to Binary Tree | GeeksforGeeks

Introduction to Binary Tree


Last Updated : 14 Feb, 2025

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

https://www.geeksforgeeks.org/introduction-to-binary-tree/?ref=lbp 1/17
3/30/25, 4:07 PM Introduction to Binary Tree | GeeksforGeeks

Binary Tree Representation

Create/Declare a Node of a Binary Tree

Syntax to declare a Node of Binary Tree in different languages:

C++ C Java Python C# 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)

https://www.geeksforgeeks.org/introduction-to-binary-tree/?ref=lbp 2/17
3/30/25, 4:07 PM Introduction to Binary Tree | GeeksforGeeks

Creating a Binary Tree having three nodes

C++ C Java Python C# 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

https://www.geeksforgeeks.org/introduction-to-binary-tree/?ref=lbp 3/17
3/30/25, 4:07 PM Introduction to Binary Tree | GeeksforGeeks

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


https://www.geeksforgeeks.org/introduction-to-binary-tree/?ref=lbp 4/17
3/30/25, 4:07 PM Introduction to Binary Tree | GeeksforGeeks

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


Full Binary Tree
Degenerate Binary Tree
Skewed Binary Trees
On the basis of Completion of Levels
Complete Binary Tree
Perfect Binary Tree
Balanced Binary Tree
On the basis of Node Values:
Binary Search Tree
AVL Tree
Red Black Tree
B Tree
B+ Tree
Segment Tree

Operations On Binary Tree


Following is a list of common operations that can be performed on a
binary tree:

https://www.geeksforgeeks.org/introduction-to-binary-tree/?ref=lbp 5/17
3/30/25, 4:07 PM Introduction to Binary Tree | GeeksforGeeks

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:

Preorder Traversal (current-left-right): Visits the node first, then


left subtree, then right subtree.
Inorder Traversal (left-current-right): Visits left subtree, then the
node, then the right subtree.
Postorder Traversal (left-right-current): Visits left subtree, then
right subtree, then the node.

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++ C Java Python C# 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);
console.log(node.data + " ");
inOrderDFS(node.right);
}

// Pre-order DFS: Root, Left, Right


function preOrderDFS(node) {
if (node === null) return;

https://www.geeksforgeeks.org/introduction-to-binary-tree/?ref=lbp 6/17
3/30/25, 4:07 PM Introduction to Binary Tree | GeeksforGeeks
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);

Output

In-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

https://www.geeksforgeeks.org/introduction-to-binary-tree/?ref=lbp 7/17
3/30/25, 4:07 PM Introduction to Binary Tree | GeeksforGeeks

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++ C Java Python C# 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;
https://www.geeksforgeeks.org/introduction-to-binary-tree/?ref=lbp 8/17
3/30/25, 4:07 PM Introduction to Binary Tree | GeeksforGeeks
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();

Output

Inorder 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++ C Java Python C# JavaScript

https://www.geeksforgeeks.org/introduction-to-binary-tree/?ref=lbp 9/17
3/30/25, 4:07 PM Introduction to Binary Tree | GeeksforGeeks

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`);
}

Output

6 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

https://www.geeksforgeeks.org/introduction-to-binary-tree/?ref=lbp 10/17
3/30/25, 4:07 PM Introduction to Binary Tree | GeeksforGeeks

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++ C Java Python C# 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


https://www.geeksforgeeks.org/introduction-to-binary-tree/?ref=lbp 11/17
3/30/25, 4:07 PM Introduction to Binary Tree | GeeksforGeeks
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);
console.log(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();

Output

Original tree (in-order): 5 3 6 2 4


Tree after deleting 3 (in-order): 5 6 2 4

Auxiliary Operations On Binary Tree


Finding the height of the tree
Find level of a node in a Binary tree
Finding the size of the entire tree

Complexity Analysis of Binary Tree Operations


Here’s the complexity analysis for specific binary tree operations:

https://www.geeksforgeeks.org/introduction-to-binary-tree/?ref=lbp 12/17
3/30/25, 4:07 PM Introduction to Binary Tree | GeeksforGeeks

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.

https://www.geeksforgeeks.org/introduction-to-binary-tree/?ref=lbp 13/17
3/30/25, 4:07 PM Introduction to Binary Tree | GeeksforGeeks

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.

https://www.geeksforgeeks.org/introduction-to-binary-tree/?ref=lbp 14/17
3/30/25, 4:07 PM Introduction to Binary Tree | GeeksforGeeks

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.

5. How do you perform tree traversal in a binary tree?

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?


https://www.geeksforgeeks.org/introduction-to-binary-tree/?ref=lbp 15/17
3/30/25, 4:07 PM Introduction to Binary Tree | GeeksforGeeks

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:

Binary Search Tree (BST)


AVL Tree

https://www.geeksforgeeks.org/introduction-to-binary-tree/?ref=lbp 16/17
3/30/25, 4:07 PM Introduction to Binary Tree | GeeksforGeeks

https://www.geeksforgeeks.org/introduction-to-binary-tree/?ref=lbp 17/17
3/30/25, 4:07 PM Properties of Binary Tree | GeeksforGeeks

Properties of Binary Tree


Last Updated : 24 Mar, 2025

This post explores the fundamental properties of a binary tree,


covering its structure, characteristics, and key relationships between
nodes, edges, height, and levels

Binary tree representation

Note: Height of root node is considered as 0.

Properties of Binary Trees

1. Maximum Nodes at Level ‘l’

A binary tree can have at most 2l nodes at level l.

Level Definition: The number of edges in the path from the root to
a node. The root is at level 0.
Proof by Induction:

Base case: For root (l = 0), nodes = 20 = 1.

https://www.geeksforgeeks.org/properties-of-binary-tree/?ref=lbp 1/5
3/30/25, 4:07 PM Properties of Binary Tree | GeeksforGeeks

Inductive step: If level l has 2l nodes, then the next level has at
most twice as many:

2×2l = 2l+1

2. Maximum Nodes in a Binary Tree of Height ‘h’

A binary tree of height h can have at most 2h+1 – 1 nodes.

Height Definition: The longest path from the root to a leaf node.
Please note that a tree with only one root node is considered to
have height 0 and an empty tree (or root is NULL) is considered to
have height “-1”

Formula Derivation: A tree has the maximum nodes when all


levels are completely filled. Summing nodes at each level:

1 + 2 + 4 +…+ 2h = 2h+1 – 1

Alternate Height Convention: Some books consider a tree with


only one root node is considered to have height 1 and an empty tree
(or root is NULL) is considered to have height 0. making the formula
2h – 1.

3. Minimum Height for ‘N’ Nodes

The minimum possible height for N nodes is ⌊log⁡2N⌋.

Explanation: A binary tree with height h can have at most 2h+1 – 1


nodes.

Rearranging:

N ≤ 2h+1 − 1
2h+1 ≥ N+1
https://www.geeksforgeeks.org/properties-of-binary-tree/?ref=lbp 2/5
3/30/25, 4:07 PM Properties of Binary Tree | GeeksforGeeks

h ≥ log2​(N+1) – 1 (Taking log2 both sides)


h ≥ ⌊log2​N⌋

This means a binary tree with N nodes must have at least ⌊log⁡2N⌋
levels.

4. Minimum Levels for ‘L’ Leaves

A binary tree with L leaves must have at least ⌊log⁡2L⌋ levels.

Why? A tree has the maximum number of leaves when all levels are
fully filled.

From Property 1:
L ≤ 2l ( l is the level where leaves appear)

Solving for l:
lmin = ⌊log⁡2L⌋

This gives the minimum levels needed to accommodate L leaves.

5. Nodes with Two Children vs. Leaf Nodes

In a full binary tree (where every node has either 0 or 2 children), the
number of leaf nodes (L) is always one more than the internal nodes
(T) with two children:

L=T+1

Proof:

A full binary tree has a total of 2h+1 – 1 nodes.

Leaves are at the last level: L = 2h.

Internal nodes: T =2h (2−1) − 1= 2h – 1.


https://www.geeksforgeeks.org/properties-of-binary-tree/?ref=lbp 3/5
3/30/25, 4:07 PM Properties of Binary Tree | GeeksforGeeks

Simplifies to L=T+1

6. Total Edges in a Binary Tree

In any non-empty binary tree with n nodes, the total number of edges
is n – 1.

Every node (except the root) has exactly one parent, and each
parent-child connection represents an edge.

Since there are n nodes, there must be n – 1 edges.

Additional Key Properties

Node Relationships

Each node has at most two children.


0 children → Leaf Node
1 child → Unary Node
2 children → Binary Node

Types of Binary Trees

Full Binary Tree → Every non-leaf node has exactly two children.
Complete Binary Tree → All levels are fully filled except possibly
the last, which is filled from left to right.
Perfect Binary Tree → Every level is completely filled, and all
leaves are at the same depth.
Balanced Binary Tree → The left and right subtrees differ in
height by at most 1.

Tree Traversal Methods

https://www.geeksforgeeks.org/properties-of-binary-tree/?ref=lbp 4/5
3/30/25, 4:07 PM Properties of Binary Tree | GeeksforGeeks

Tree traversal is categorized into Depth-First Search (DFS) and


Breadth-First Search (BFS):

DFS Traversals: Explore one branch fully before backtracking.


In-Order (LNR): Left → Node → Right (retrieves BST
elements in sorted order).
Pre-Order (NLR): Node → Left → Right (used for tree
reconstruction).
Post-Order (LRN): Left → Right → Node (helps in deleting
or evaluating expressions).
BFS Traversals: Visit nodes level by level.
Level-Order: Processes nodes from top to bottom (used in
shortest path algorithms).
Zig-Zag Traversal: Alternates left-to-right and right-to-
left at each level (used in hierarchical structures).

Related Articles:
See Handshaking Lemma and Tree for proof
Different types of Binary Trees and their properties
Introduction to Binary Tree in set 1

https://www.geeksforgeeks.org/properties-of-binary-tree/?ref=lbp 5/5
3/30/25, 4:08 PM Applications, Advantages and Disadvantages of Binary Tree | GeeksforGeeks

38

Applications, Advantages and Disadvantages of


Binary Tree
Last Updated : 24 Mar, 2025

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“

Applications:

SaleGeneral
Ends In 31 Applications
: 51 : 50 DSA Course DSA Interview Problems on Tree Practice Tree MCQs on Tre

DOM in HTML: Binary trees help manage the hierarchical structure


of web pages.
File Explorer: They organize file systems for efficient navigation.
Expression Evaluation: Used in calculators and compilers to evaluate
arithmetic expressions.
Routing Algorithms: Support decision-making in network routing.

https://www.geeksforgeeks.org/applications-advantages-and-disadvantages-of-binary-tree/?ref=lbp 1/8
3/30/25, 4:08 PM Applications, Advantages and Disadvantages of Binary Tree | GeeksforGeeks

Additional Uses: Various other applications that benefit from


hierarchical data organization.

Hierarchical Data Representation

File Systems & Folder Structures: Organize files and directories.


Organizational Charts: Represent corporate or institutional
hierarchies.
XML/HTML Parsing: Process structured data in documents.

Applications of Binary Search Trees (BST)

Efficient Operations: Enable quick searching, insertion, and deletion


(average time complexity: O(log n); AVL and Red-Black Trees
maintain this efficiency). Apart from these operations, additional
operations like sorted traversal, floor and ceil are also efficient.
Please note search, insert and delete are faster than array and linked
list and slower than hashing, but hashing does not allow sorted
traversal, floor and ceil operations.
Data Structures: Implement associative arrays, maps, and sets while
keeping data sorted.

Applications of Binary Heap Trees

Expression Trees: Represent arithmetic expressions where internal


nodes are operators and leaf nodes are operands.
Use Cases: Common in compilers and calculators.
Huffman Coding Trees: Essential in data compression (e.g., Huffman
coding for lossless compression).
Decision Trees:
Machine Learning: Serve as models for classification and
regression problems.
Conditional Processes: Represent decision-making steps.
Traversal Operations: Preorder, inorder, and postorder traversals aid
in tasks like expression evaluation and tree reconstruction.

https://www.geeksforgeeks.org/applications-advantages-and-disadvantages-of-binary-tree/?ref=lbp 2/8
3/30/25, 4:08 PM Applications, Advantages and Disadvantages of Binary Tree | GeeksforGeeks

Advantages of Binary Trees

Structured Organization: Offers a clear, hierarchical data structure.


Efficient Searching and Sorting: BSTs facilitate fast data operations.
Balanced Storage: Variants like AVL and Red-Black trees ensure
balanced performance (O(log n)).
Flexibility: Adaptable to various specialized structures (e.g., heaps,
BSTs).
Recursion Support: Naturally aligns with recursive algorithms.
Scalability: Suitable for managing large dynamic datasets.

Disadvantages of Binary Trees

Skewed Trees: Unbalanced trees can degrade performance to O(n),


similar to linked lists.
Memory Overhead: Additional pointers in each node increase
memory usage.
Complex Implementation:Balancing trees (e.g., AVL, Red-Black)
requires sophisticated rotations.
Limited Degree: Restricts each node to two children, which might
not be ideal for some applications.

Master Data Structures and Algorithms at your own pace with our
DSA Self-Paced course. In just 90 days, you’ll cover core concepts,
solve real-world problems, and sharpen your problem-solving
skills. Take the Three 90 Challenge: complete 90% of the course in
90 days and get a 90% refund. Stay motivated, track progress, and
achieve DSA mastery. Start today!

Comment More info Next Article


Binary Tree (Array
Placement Training Program implementation)

https://www.geeksforgeeks.org/applications-advantages-and-disadvantages-of-binary-tree/?ref=lbp 3/8
3/30/25, 4:08 PM Applications, Advantages and Disadvantages of Binary Tree | GeeksforGeeks

Similar Reads
Applications, Advantages and Disadvantages of Binary Search Tree
A Binary Search Tree (BST) is a data structure used to storing data in a
sorted manner. Each node in a Binary Search Tree has at most two…

2 min read

Applications, Advantages and Disadvantages of Red-Black Tree


Red-Black Tree is one type of self-balancing tree where each node has
one extra bit that is often interpreted as colour of the node. This bit (the…

4 min read

Applications, Advantages and Disadvantages of Segment Tree


First, let us understand why we need it prior to landing on the
introduction so as to get why this concept was introduced. Suppose we…

4 min read

Applications, Advantages and Disadvantages of Binary Search


Binary Search is defined as a searching algorithm used in a sorted array
by repeatedly dividing the search interval in half. The idea of binary sear…

2 min read

Applications, Advantages and Disadvantages of Branch and Bound…


Branch and bound algorithm is a method used in computer science to find
the best solution to optimization problems. It systematically explores all…

2 min read

Applications, Advantages and Disadvantages of Graph


Graph is a non-linear data structure that contains nodes (vertices) and
edges. A graph is a collection of set of vertices and edges (formed by…

7 min read

Applications, Advantages and Disadvantages of Stack


https://www.geeksforgeeks.org/applications-advantages-and-disadvantages-of-binary-tree/?ref=lbp 4/8
3/30/25, 4:08 PM Applications, Advantages and Disadvantages of Binary Tree | GeeksforGeeks

A stack is a linear data structure in which the insertion of a new element


and removal of an existing element takes place at the same end…

2 min read

Applications, Advantages and Disadvantages of Queue


A Queue is a linear data structure. This data structure follows a particular
order in which the operations are performed. The order is First In First O…

5 min read

Applications, Advantages and Disadvantages of Doubly Linked List


Doubly linked list is a type of linked list in which nodes contains
information and two pointers i.e. left pointer and right pointer. The left…

4 min read

Applications, Advantages and Disadvantages of Directed Graph


Directed graphs are graphs that have directed edges between the nodes.
If a directed edge points from u to v then, v is adjacent to u and u is…

2 min read

Corporate & Communications Address:


A-143, 7th Floor, Sovereign Corporate
Tower, Sector- 136, Noida, Uttar Pradesh
(201305)

Registered Address:
K 061, Tower K, Gulshan Vivante
Apartment, Sector 137, Noida, Gautam
Buddh Nagar, Uttar Pradesh, 201305

https://www.geeksforgeeks.org/applications-advantages-and-disadvantages-of-binary-tree/?ref=lbp 5/8
3/30/25, 4:08 PM Applications, Advantages and Disadvantages of Binary Tree | GeeksforGeeks

Advertise with us

Company Explore
About Us Job-A-Thon Hiring Challenge
Legal Hack-A-Thon
Privacy Policy GfG Weekly Contest
Careers Offline Classes (Delhi/NCR)
In Media DSA in JAVA/C++
Contact Us Master System Design
GfG Corporate Solution Master CP
Placement Training Program GeeksforGeeks Videos
Geeks Community

Languages DSA
Python Data Structures
Java Algorithms
C++ DSA for Beginners
PHP Basic DSA Problems
GoLang DSA Roadmap
SQL DSA Interview Questions
R Language Competitive Programming
Android Tutorial

Data Science & ML Web Technologies


Data Science With Python HTML
Data Science For Beginner CSS
Machine Learning JavaScript
ML Maths TypeScript
Data Visualisation ReactJS
Pandas NextJS
NumPy NodeJs
NLP Bootstrap
Deep Learning Tailwind CSS

Python Tutorial Computer Science


Python Programming Examples GATE CS Notes
Django Tutorial Operating Systems
Python Projects Computer Network
Python Tkinter Database Management System
Web Scraping Software Engineering
OpenCV Tutorial Digital Logic Design
Python Interview Question Engineering Maths

DevOps System Design


Git High Level Design
AWS Low Level Design
Docker UML Diagrams
Kubernetes Interview Guide

https://www.geeksforgeeks.org/applications-advantages-and-disadvantages-of-binary-tree/?ref=lbp 6/8
3/30/25, 4:08 PM Applications, Advantages and Disadvantages of Binary Tree | GeeksforGeeks

Azure Design Patterns


GCP OOAD
DevOps Roadmap System Design Bootcamp
Interview Questions

School Subjects Software and Tools


Mathematics AI Tools Directory
Physics Marketing Tools Directory
Chemistry Accounting Software Directory
Biology HR Management Tools
Social Science Editing Software Directory
English Grammar Microsoft Products and Apps
Figma Tutorial

Databases Preparation Corner


SQL Company-Wise Recruitment Process
MYSQL Resume Templates
PostgreSQL Aptitude Preparation
PL/SQL Puzzles
MongoDB Company-Wise Preparation
Companies
Colleges

Competitive Exams More Tutorials


JEE Advanced Software Development
UGC NET Software Testing
UPSC Product Management
SSC CGL Project Management
SBI PO Linux
SBI Clerk Excel
IBPS PO All Cheat Sheets
IBPS Clerk Recent Articles

Free Online Tools Write & Earn


Typing Test Write an Article
Image Editor Improve an Article
Code Formatters Pick Topics to Write
Code Converters Share your Experiences
Currency Converter Internships
Random Number Generator
Random Password Generator

DSA/Placements Development/Testing
DSA - Self Paced Course JavaScript Full Course
DSA in JavaScript - Self Paced Course React JS Course
DSA in Python - Self Paced React Native Course
C Programming Course Online - Learn C with Data Structures Django Web Development Course
Complete Interview Preparation Complete Bootstrap Course
Master Competitive Programming Full Stack Development - [LIVE]

https://www.geeksforgeeks.org/applications-advantages-and-disadvantages-of-binary-tree/?ref=lbp 7/8
3/30/25, 4:08 PM Applications, Advantages and Disadvantages of Binary Tree | GeeksforGeeks

Core CS Subject for Interview Preparation JAVA Backend Development - [LIVE]


Mastering System Design: LLD to HLD Complete Software Testing Course [LIVE]
Tech Interview 101 - From DSA to System Design [LIVE] Android Mastery with Kotlin [LIVE]
DSA to Development [HYBRID]
Placement Preparation Crash Course [LIVE]

Machine Learning/Data Science Programming Languages


Complete Machine Learning & Data Science Program - [LIVE] C Programming with Data Structures
Data Analytics Training using Excel, SQL, Python & PowerBI - C++ Programming Course
[LIVE] Java Programming Course
Data Science Training Program - [LIVE] Python Full Course
Mastering Generative AI and ChatGPT
Data Science Course with IBM Certification

Clouds/Devops GATE 2026


DevOps Engineering GATE CS Rank Booster
AWS Solutions Architect Certification GATE DA Rank Booster
Salesforce Certified Administrator Course GATE CS & IT Course - 2026
GATE DA Course 2026
GATE Rank Predictor

@GeeksforGeeks, Sanchhaya Education Private Limited, All rights reserved

https://www.geeksforgeeks.org/applications-advantages-and-disadvantages-of-binary-tree/?ref=lbp 8/8
3/30/25, 4:08 PM Binary Tree (Array implementation) | GeeksforGeeks

Binary Tree (Array implementation)


Last Updated : 06 Apr, 2023

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 of given Binary Tree from this given
representation. Do refer in order to understand how to construct
binary tree from given parent array representation.

Ways to represent:

Trees can be represented in two ways as listed below:

1. Dynamic Node Representation (Linked Representation).


2. Array Representation (Sequential Representation).

Now, we are going to talk about the sequential representation of the


trees. In order to represent a tree using an array, the numbering of
nodes can start either from 0–(n-1) or 1– n, consider the below
illustration as follows:

Illustration:

A(0)
/ \
B(1) C(2)
/ \ \
D(3) E(4) F(6)
OR,
A(1)
/ \
B(2) C(3)

https://www.geeksforgeeks.org/binary-tree-array-implementation/?ref=lbp 1/3
3/30/25, 4:08 PM Binary Tree (Array implementation) | GeeksforGeeks

/ \ \
D(4) E(5) F(7)

Procedure:

Note: father, left_son and right_son are the values of indices of


the array.

Case 1: (0—n-1)

if (say)father=p;
then left_son=(2*p)+1;
and right_son=(2*p)+2;

Case 2: 1—n

if (say)father=p;
then left_son=(2*p);
and right_son=(2*p)+1;

Implementation:

// JavaScript implementation of tree using array


// numbering starting from 0 to n-1.
const tree = Array(10).fill(null);

function root(key) {
if (tree[0] != null) {
console.log("Tree already had root");
} else {
tree[0] = key;
}
}

function setLeft(key, parent) {


if (tree[parent] == null) {
console.log(`Can't set child at ${(parent * 2) + 1}, no parent fo
} else {
tree[(parent * 2) + 1] = key;
}
}

https://www.geeksforgeeks.org/binary-tree-array-implementation/?ref=lbp 2/3
3/30/25, 4:08 PM Binary Tree (Array implementation) | GeeksforGeeks

function setRight(key, parent) {


if (tree[parent] == null) {
console.log(`Can't set child at ${(parent * 2) + 2}, no parent fo
} else {
tree[(parent * 2) + 2] = key;
}
}

function printTree() {
for (let i = 0; i < 10; i++) {
if (tree[i] != null) {
console.log(tree[i]);
} else {
console.log("-");
}
}
}

// Driver Code
root("A");
setLeft("B", 0);
setRight("C", 0);
setLeft("D", 1);
setRight("E", 1);
setRight("F", 2);
printTree();

// This code is contributed by lokeshpotta20

Output

ABCDE-F---

Time complexity: O(log n) since using heap to create a binary tree


Space complexity: O(1)

https://www.geeksforgeeks.org/binary-tree-array-implementation/?ref=lbp 3/3
3/30/25, 4:08 PM Maximum Depth of Binary Tree | GeeksforGeeks

Maximum Depth of Binary Tree


Last Updated : 31 Jan, 2025

Given a binary tree, the task is to find the maximum depth of the tree.
The maximum depth or height of the tree is the number of edges in
the tree from the root to the deepest node.

Examples:

Input:

Output: 2
Explanation: The longest path from the root (node 12) goes
through node 8 to node 5, which has 2 edges.

Input:

https://www.geeksforgeeks.org/find-the-maximum-depth-or-height-of-a-tree/?ref=lbp 1/7
3/30/25, 4:08 PM Maximum Depth of Binary Tree | GeeksforGeeks

Output: 3
Explanation: The longest path from the root (node 1) to a leaf
node 6 with 3 edge.

Table of Content
[Approach 1] Using Recursion – O(n) Time and O(h) Space
[Approach 2] Level Order Traversal using Null Delimiter – O(n)
Time and O(n) Space
[Approach 3] Level Order Traversal without using Null Delimiter –
O(n) Time and O(n) Space

[Approach 1] Using Recursion – O(n) Time and O(h) Space

The idea is to recursively calculate the height of the left and the
right subtrees of a node and then find height to the node as max
of the heights of two children plus 1.

Follow the steps below to solve the problem:

If the tree is empty, return -1.


Otherwise, do the following:
Get the height of the left subtree recursively, i.e., call
height(node->left).
Get the height of the right subtree recursively, i.e., call
height(node->right).
https://www.geeksforgeeks.org/find-the-maximum-depth-or-height-of-a-tree/?ref=lbp 2/7
3/30/25, 4:08 PM Maximum Depth of Binary Tree | GeeksforGeeks

Compute the maximum of the heights of the left and right


subtrees and add 1 to it for the current node.
height = max(height of left subtree, height of right
subtree) + 1.
Return the height.

C++ C Java Python C# JavaScript

▸ {...}

// Returns height which is the number of edges


// along the longest path from the root node down
// to the farthest leaf node.
function height(root) {
if (root === null) {
return -1;
}

// compute the height of left and right subtrees


let lHeight = height(root.left);
let rHeight = height(root.right);

return Math.max(lHeight, rHeight) + 1;


}

▸ {...}

Output

Below is the illustration of above approach:

Example: Consider the following tree –

https://www.geeksforgeeks.org/find-the-maximum-depth-or-height-of-a-tree/?ref=lbp 3/7
3/30/25, 4:08 PM Maximum Depth of Binary Tree | GeeksforGeeks

height(’12’) = max(height(‘8′), height(’18’)) + 1 = 1 + 1 = 2


because recursively:
height(‘8’) = max(height(‘5′), height(’11’)) + 1 = 0 + 1 = 1
height(’18’) = max(height(NULL), height(‘NULL’)) + 1 = (-1) + 1 =
0
height(“5”) = max(height(NULL), height(‘NULL’)) + 1 = (-1) + 1 =
0
height(“11”) = max(height(NULL), height(‘NULL’)) + 1 = (-1) + 1 =
0

[Approach 2] Level Order Traversal using Null Delimiter – O(n)


Time and O(n) Space

If we take a closer look at the breadth first traversal, we can


notice that after we process the last node of the current level,
the queue contains all the nodes of next level. We use this
property and insert a special NULL into the queue to indicate
end of a level.

Follow the steps below to solve the problem:

Traverse the tree in level order traversal starting from root.


Initialize an empty queue q, a variable depth. Now push root and
then push null into the q to indicate end of the first level.
Run a while loop till q is not empty.
Store the front element of q and pop out the front
element.
https://www.geeksforgeeks.org/find-the-maximum-depth-or-height-of-a-tree/?ref=lbp 4/7
3/30/25, 4:08 PM Maximum Depth of Binary Tree | GeeksforGeeks

If the front of q is NULL, it means we have processed the


last node of current level and now the queue contains all
the nodes of next level. So we increment depth and insert
a NULL in queue indicating the end of the next level.
Else if the element is not NULL then check for its left and
right children and if they are not NULL push them into q.
Return depth – 1, as the number of edges encountered will be one
less than number of nodes.

C++ Java Python C# JavaScript

▸ {...}

// Function to find the height of the tree


function height(root) {
if (root === null) return 0;

// Initializing a variable to count


// the depth of the tree
let depth = 0;
let q = [];

// Pushing the first level element


// along with null
q.push(root);
q.push(null);

while (q.length > 0) {


let curr = q.shift();

// When null is encountered, increment the depth


if (curr === null) {
depth++;

// If queue still has elements left,


// push null again to the queue
if (q.length > 0) {
q.push(null);
}
}
else {

// If null is not encountered,


// keep moving
if (curr.left) q.push(curr.left);
if (curr.right) q.push(curr.right);
}
}
return depth - 1;
}

https://www.geeksforgeeks.org/find-the-maximum-depth-or-height-of-a-tree/?ref=lbp 5/7
3/30/25, 4:08 PM Maximum Depth of Binary Tree | GeeksforGeeks

▸ {...}

Output

[Approach 3] Level Order Traversal without using Null


Delimiter – O(n) Time and O(n) Space

This method also uses the same concept that when we process
the last node of a current level, the next level is completely in
the queue. Instead of adding a null in the Queue. Simply
increase the counter when the level increases and push the
children of current node into the queue, then remove all the
nodes from the queue of the current Level.

C++ Java Python C# JavaScript

▸ {...}

// Function to find the height of the tree


function height(root) {
if (root === null) {
return 0;
}

// Initializing a queue to traverse


// the tree level by level
let queue = [root];
let depth = 0;

// Loop until the queue is empty


while (queue.length > 0) {
let levelSize = queue.length;

// Traverse all nodes at the current level


for (let i = 0; i < levelSize; i++) {
let curr = queue.shift();

if (curr.left) {
queue.push(curr.left);
}
if (curr.right) {
queue.push(curr.right);
}
}

https://www.geeksforgeeks.org/find-the-maximum-depth-or-height-of-a-tree/?ref=lbp 6/7
3/30/25, 4:08 PM Maximum Depth of Binary Tree | GeeksforGeeks
// Increment depth after traversing a level
depth++;
}
return depth - 1;
}

▸ {...}

Output

https://www.geeksforgeeks.org/find-the-maximum-depth-or-height-of-a-tree/?ref=lbp 7/7
3/30/25, 4:08 PM Insertion in a Binary Tree in level order | GeeksforGeeks

38

Insertion in a Binary Tree in level order


Last Updated : 24 Mar, 2025

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:

Sale Ends In 31 : 51 : 04 DSA Course DSA Interview Problems on Tree Practice Tree MCQs on Tre

https://www.geeksforgeeks.org/insertion-in-a-binary-tree-in-level-order/?ref=lbp 1/9
3/30/25, 4:08 PM Insertion in a Binary Tree in level order | GeeksforGeeks

Explanation: Node with value 12 is inserted into the binary tree at


the first position available in level order manner.

Approach:

The idea is to do an iterative level order traversal of the given tree


using queue. If we find a node whose left child is empty, we make
a new key as the left child of the node. Else if we find a node
whose right child is empty, we make the new key as the right
child. We keep traversing the tree until we find a node whose
either left or right child is empty

Below is the implementation of the above approach:

C++ Java Python C# JavaScript

// JavaScript program to insert element


// (in level order) in Binary Tree

class Node {
constructor(x) {
this.data = x;
this.left = null;
this.right = null;
}
}

// Function to insert element in binary tree


function InsertNode(root, data) {

// If the tree is empty, assign new


https://www.geeksforgeeks.org/insertion-in-a-binary-tree-in-level-order/?ref=lbp 2/9
3/30/25, 4:08 PM Insertion in a Binary Tree in level order | GeeksforGeeks
// node address to root
if (root == null) {
root = new Node(data);
return root;
}

// Else, do level order traversal until we find an empty


// place, i.e. either left child or right child of some
// node is pointing to NULL.
let q = [];
q.push(root);

while (q.length > 0) {

let curr = q.shift();

// First check left if left is null


// insert node in left otherwise chaeck for right
if (curr.left !== null)
q.push(curr.left);
else {
curr.left = new Node(data);
return root;
}

if (curr.right !== null)


q.push(curr.right);
else {
curr.right = new Node(data);
return root;
}
}
}

// Inorder traversal of a binary tree


function inorder(curr) {
if (curr == null) return;
inorder(curr.left);
process.stdout.write(curr.data + ' ');
inorder(curr.right);
}

// Constructing the binary tree


// 10
// / \
// 11 9
// / / \
// 7 15 8
let root = new Node(10);
root.left = new Node(11);
root.right = new Node(9);
root.left.left = new Node(7);
root.right.left = new Node(15);
root.right.right = new Node(8);

let key = 12;


root = InsertNode(root, key);

// After insertion 12 in binary tree


// 10

https://www.geeksforgeeks.org/insertion-in-a-binary-tree-in-level-order/?ref=lbp 3/9
3/30/25, 4:08 PM Insertion in a Binary Tree in level order | GeeksforGeeks
// / \
// 11 9
// / \ / \
// 7 12 15 8

inorder(root);

Output

7 11 12 10 15 9 8

Time Complexity: O(n) where n is the number of nodes.


Auxiliary Space: O(n)

Master Data Structures and Algorithms at your own pace with our
DSA Self-Paced course. In just 90 days, you’ll cover core concepts,
solve real-world problems, and sharpen your problem-solving
skills. Take the Three 90 Challenge: complete 90% of the course in
90 days and get a 90% refund. Stay motivated, track progress, and
achieve DSA mastery. Start today!

Comment More info


Next Article
Placement Training Program Deletion in a Binary Tree

Similar Reads
Print nodes of a Binary Search Tree in Top Level Order and Reversed…
Given a Binary Search Tree, the task is to print the nodes of the BST in the
following order: If the BST contains levels numbered from 1 to N then, th…

15+ min read

Insertion in n-ary tree in given order and Level order traversal


Given a set of parent nodes where the index of the array is the child of
each Node value, the task is to insert the nodes as a forest(multiple trees…

10 min read
https://www.geeksforgeeks.org/insertion-in-a-binary-tree-in-level-order/?ref=lbp 4/9
3/30/25, 4:08 PM Insertion in a Binary Tree in level order | GeeksforGeeks

Flatten Binary Tree in order of Level Order Traversal


Given a Binary Tree, the task is to flatten it in order of Level order traversal
of the tree. In the flattened binary tree, the left node of all the nodes mu…

7 min read

Pre Order, Post Order and In Order traversal of a Binary Tree in one…
Given a binary tree, the task is to print all the nodes of the binary tree in
Pre-order, Post-order, and In-order in one iteration. Examples: Input:…

9 min read

Given level order traversal of a Binary Tree, check if the Tree is a Min…
Given the level order traversal of a Complete Binary Tree, determine
whether the Binary Tree is a valid Min-HeapExamples:Input: level = [10,…

4 min read

Connect Nodes at same Level (Level Order Traversal)


Given a binary tree, the task is to connect the nodes that are at the same
level. Given an addition nextRight pointer for the same. Initially, all the…

9 min read

Difference between sums of odd level and even level nodes of a Bin…
Given a Binary Tree, the task is to find the difference between the sum of
nodes at the odd level and the sum of nodes at the even level.…

14 min read

Count nodes from all lower levels smaller than minimum valued no…
Given a Binary Tree, the task is for each level is to print the total number
of nodes from all lower levels which are less than or equal to every node…

11 min read

Print the nodes corresponding to the level value for each level of a…

https://www.geeksforgeeks.org/insertion-in-a-binary-tree-in-level-order/?ref=lbp 5/9
3/30/25, 4:08 PM Insertion in a Binary Tree in level order | GeeksforGeeks

Given a Binary Tree, the task for each level L is to print the Lth node of the
tree. If the Lth node is not present for any level, print -1. Note: Consider…

15 min read

Modify a Binary Tree by adding a level of nodes with given value at …


Given a Binary Tree consisting of N nodes and two integers K and L, the
task is to add one row of nodes of value K at the Lth level, such that the…

15+ min read

Corporate & Communications Address:


A-143, 7th Floor, Sovereign Corporate
Tower, Sector- 136, Noida, Uttar Pradesh
(201305)

Registered Address:
K 061, Tower K, Gulshan Vivante
Apartment, Sector 137, Noida, Gautam
Buddh Nagar, Uttar Pradesh, 201305

Advertise with us

Company Explore
About Us Job-A-Thon Hiring Challenge
Legal Hack-A-Thon
Privacy Policy GfG Weekly Contest
Careers Offline Classes (Delhi/NCR)
In Media DSA in JAVA/C++
Contact Us Master System Design
GfG Corporate Solution Master CP
Placement Training Program GeeksforGeeks Videos
Geeks Community

Languages DSA
https://www.geeksforgeeks.org/insertion-in-a-binary-tree-in-level-order/?ref=lbp 6/9
3/30/25, 4:08 PM Insertion in a Binary Tree in level order | GeeksforGeeks

Python Data Structures


Java Algorithms
C++ DSA for Beginners
PHP Basic DSA Problems
GoLang DSA Roadmap
SQL DSA Interview Questions
R Language Competitive Programming
Android Tutorial

Data Science & ML Web Technologies


Data Science With Python HTML
Data Science For Beginner CSS
Machine Learning JavaScript
ML Maths TypeScript
Data Visualisation ReactJS
Pandas NextJS
NumPy NodeJs
NLP Bootstrap
Deep Learning Tailwind CSS

Python Tutorial Computer Science


Python Programming Examples GATE CS Notes
Django Tutorial Operating Systems
Python Projects Computer Network
Python Tkinter Database Management System
Web Scraping Software Engineering
OpenCV Tutorial Digital Logic Design
Python Interview Question Engineering Maths

DevOps System Design


Git High Level Design
AWS Low Level Design
Docker UML Diagrams
Kubernetes Interview Guide
Azure Design Patterns
GCP OOAD
DevOps Roadmap System Design Bootcamp
Interview Questions

School Subjects Software and Tools


Mathematics AI Tools Directory
Physics Marketing Tools Directory
Chemistry Accounting Software Directory
Biology HR Management Tools
Social Science Editing Software Directory
English Grammar Microsoft Products and Apps
Figma Tutorial

Databases Preparation Corner


https://www.geeksforgeeks.org/insertion-in-a-binary-tree-in-level-order/?ref=lbp 7/9
3/30/25, 4:08 PM Insertion in a Binary Tree in level order | GeeksforGeeks

SQL Company-Wise Recruitment Process


MYSQL Resume Templates
PostgreSQL Aptitude Preparation
PL/SQL Puzzles
MongoDB Company-Wise Preparation
Companies
Colleges

Competitive Exams More Tutorials


JEE Advanced Software Development
UGC NET Software Testing
UPSC Product Management
SSC CGL Project Management
SBI PO Linux
SBI Clerk Excel
IBPS PO All Cheat Sheets
IBPS Clerk Recent Articles

Free Online Tools Write & Earn


Typing Test Write an Article
Image Editor Improve an Article
Code Formatters Pick Topics to Write
Code Converters Share your Experiences
Currency Converter Internships
Random Number Generator
Random Password Generator

DSA/Placements Development/Testing
DSA - Self Paced Course JavaScript Full Course
DSA in JavaScript - Self Paced Course React JS Course
DSA in Python - Self Paced React Native Course
C Programming Course Online - Learn C with Data Structures Django Web Development Course
Complete Interview Preparation Complete Bootstrap Course
Master Competitive Programming Full Stack Development - [LIVE]
Core CS Subject for Interview Preparation JAVA Backend Development - [LIVE]
Mastering System Design: LLD to HLD Complete Software Testing Course [LIVE]
Tech Interview 101 - From DSA to System Design [LIVE] Android Mastery with Kotlin [LIVE]
DSA to Development [HYBRID]
Placement Preparation Crash Course [LIVE]

Machine Learning/Data Science Programming Languages


Complete Machine Learning & Data Science Program - [LIVE] C Programming with Data Structures
Data Analytics Training using Excel, SQL, Python & PowerBI - C++ Programming Course
[LIVE] Java Programming Course
Data Science Training Program - [LIVE] Python Full Course
Mastering Generative AI and ChatGPT
Data Science Course with IBM Certification

Clouds/Devops GATE 2026


https://www.geeksforgeeks.org/insertion-in-a-binary-tree-in-level-order/?ref=lbp 8/9
3/30/25, 4:08 PM Insertion in a Binary Tree in level order | GeeksforGeeks

DevOps Engineering GATE CS Rank Booster


AWS Solutions Architect Certification GATE DA Rank Booster
Salesforce Certified Administrator Course GATE CS & IT Course - 2026
GATE DA Course 2026
GATE Rank Predictor

@GeeksforGeeks, Sanchhaya Education Private Limited, All rights reserved

https://www.geeksforgeeks.org/insertion-in-a-binary-tree-in-level-order/?ref=lbp 9/9
3/30/25, 4:09 PM Deletion in a Binary Tree | GeeksforGeeks

Deletion in a Binary Tree


Last Updated : 22 Oct, 2024

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 the last element.

Examples :

Input : key = 10

Output:

https://www.geeksforgeeks.org/deletion-binary-tree/?ref=lbp 1/6
3/30/25, 4:09 PM Deletion in a Binary Tree | GeeksforGeeks

Explanation: As the bottom & rightmost node in the above


binary tree is 30 , replace the key node ie. 10 with 30 and
remove the bottom & rightmost node.

Input : key = 20

Output:

https://www.geeksforgeeks.org/deletion-binary-tree/?ref=lbp 2/6
3/30/25, 4:09 PM Deletion in a Binary Tree | GeeksforGeeks

Explanation: As the bottom & rightmost node in the above


binary tree is 40, replace the key node ie. 20 with 40 and remove
the bottom & rightmost node.

Approach:

The idea is to traverse the tree in level order manner. To perform


the Deletion in a Binary Tree follow below:

Starting at the root, find the deepest and rightmost node in


the binary tree and the node which we want to delete.
Replace the deepest rightmost node’s data with the node to
be deleted.
Then delete the deepest rightmost node.

Below is the illustration of above approach:

https://www.geeksforgeeks.org/deletion-binary-tree/?ref=lbp 3/6
3/30/25, 4:09 PM Deletion in a Binary Tree | GeeksforGeeks

Below is the implementation of the above approach:

C++ Java Python C# JavaScript

// JavaScript program to delete a specific


// element in a binary tree

class Node {
constructor(data) {
this.data = data;
this.left = null;
this.right = null;
}
}

// Function to delete the deepest node in


// a binary tree
function deleteDeepest(root, dNode) {
let queue = [];
queue.push(root);

while (queue.length !== 0) {


let curr = queue.shift();

// If current node is the deepest


// node, delete it
if (curr === dNode) {
curr = null;
return;
}

// Check the right child first


if (curr.right) {
if (curr.right === dNode) {
curr.right = null;
return;
} else {
queue.push(curr.right);

https://www.geeksforgeeks.org/deletion-binary-tree/?ref=lbp 4/6
3/30/25, 4:09 PM Deletion in a Binary Tree | GeeksforGeeks
}
}

// Check the left child


if (curr.left) {
if (curr.left === dNode) {
curr.left = null;
return;
} else {
queue.push(curr.left);
}
}
}
}

// Function to delete the node with the given key


function deletion(root, key) {

if (root === null) return null;

// If the tree has only one node


if (root.left === null && root.right === null) {
if (root.data === key) return null;
else return root;
}

let queue = [];


queue.push(root);

let keyNode = null;


let curr = null;

// Level order traversal to find the


// deepest node and the key node
while (queue.length !== 0) {
curr = queue.shift();

// If current node is the key node


if (curr.data === key) keyNode = curr;

if (curr.left) queue.push(curr.left);
if (curr.right) queue.push(curr.right);
}

// If the key node is found, replace its data


// with the deepest node's data
if (keyNode !== null) {

// Store the deepest node's data


let x = curr.data;

// Replace the key node's data with the


// deepest node's data
keyNode.data = x;

// Delete the deepest node


deleteDeepest(root, curr);
}

https://www.geeksforgeeks.org/deletion-binary-tree/?ref=lbp 5/6
3/30/25, 4:09 PM Deletion in a Binary Tree | GeeksforGeeks
return root;
}

// Inorder traversal of a binary tree


function inorder(curr) {
if (curr === null) return;
inorder(curr.left);
console.log(curr.data + " ");
inorder(curr.right);
}

// Construct the binary tree


let root = new Node(10);
root.left = new Node(11);
root.right = new Node(9);
root.left.left = new Node(7);
root.left.right = new Node(12);
root.right.left = new Node(15);
root.right.right = new Node(8);

let key = 11;


root = deletion(root, key);
inorder(root);

Output

7 8 12 10 15 9

Time complexity: O(n), where n is number of nodes.


Auxiliary Space: O(n)

Note: We can also replace the node’s data that is to be deleted with
any node whose left and right child points to NULL but we only use
deepest node in order to maintain the Balance of a binary tree.

https://www.geeksforgeeks.org/deletion-binary-tree/?ref=lbp 6/6
3/30/25, 4:09 PM Enumeration of Binary Trees | GeeksforGeeks

38

Enumeration of Binary Trees


Last Updated : 26 Oct, 2021

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 Binary Trees can be there with n


nodes?

For n = 1, there is only one tree


o

For n = 2, there are two trees


o o
/ \
o o

https://www.geeksforgeeks.org/enumeration-of-binary-trees/?ref=lbp 1/8
3/30/25, 4:09 PM Enumeration of Binary Trees | GeeksforGeeks

For n = 3, there are five trees


o o o o o
/ \ / \ / \
o o o o o o
/ \ \ /
o o o o

The idea is to consider all possible pairs of counts for nodes in left and
right subtrees and multiply the counts for a particular pair. Finally, add
the results of all pairs.

For example, let T(n) be count for n nodes.


T(0) = 1 [There is only 1 empty tree]
T(1) = 1
T(2) = 2

T(3) = T(0)*T(2) + T(1)*T(1) + T(2)*T(0) = 1*2 + 1*1 + 2*1 = 5

T(4) = T(0)*T(3) + T(1)*T(2) + T(2)*T(1) + T(3)*T(0)


= 1*5 + 1*2 + 2*1 + 5*1
= 14

The above pattern basically represents n’th Catalan Numbers. First few
Catalan numbers are 1 1 2 5 14 42 132 429 1430 4862,…

Here,
T(i-1) represents the number of nodes on the left-sub-tree
T(n?i-1) represents the number of nodes on the right-sub-tree

n’th Catalan Number can also be evaluated using the direct formula.

https://www.geeksforgeeks.org/enumeration-of-binary-trees/?ref=lbp 2/8
3/30/25, 4:09 PM Enumeration of Binary Trees | GeeksforGeeks

T(n) = (2n)! / (n+1)!n!

The number of Binary Search Trees (BST) with n nodes is also the same
as the number of unlabelled trees. The reason for this is simple, in BST
also we can make any key a root, If the root is i’th key in sorted order,
then i-1 keys can go on one side, and (n-i) keys can go on another side.

How many labeled Binary Trees can be there with n nodes?


To count labeled trees, we can use the above count for unlabelled trees.
The idea is simple, every unlabelled tree with n nodes can create n!
different labeled trees by assigning different permutations of labels to
all nodes.
Sale Ends In 31 : 50 : 37 DSA Course DSA Interview Problems on Tree Practice Tree MCQs on Tre

Therefore,

Number of Labelled Trees = (Number of unlabelled trees) * n!


= [(2n)! / (n+1)!n!] × n!

For example for n = 3, there are 5 * 3! = 5*6 = 30 different labelled


trees

Master Data Structures and Algorithms at your own pace with our
DSA Self-Paced course. In just 90 days, you’ll cover core concepts,
solve real-world problems, and sharpen your problem-solving
skills. Take the Three 90 Challenge: complete 90% of the course in
90 days and get a 90% refund. Stay motivated, track progress, and
achieve DSA mastery. Start today!

https://www.geeksforgeeks.org/enumeration-of-binary-trees/?ref=lbp 3/8
3/30/25, 4:09 PM Enumeration of Binary Trees | GeeksforGeeks

Comment More info


Next Article
Placement Training Program Types of Binary Tree

Similar Reads
Total number of possible Binary Search Trees and Binary Trees with …
Given an integer n, the task is to find the total number of unique Binary
Search trees And unique Binary trees that can be made using values fro…

7 min read

Introduction to Generic Trees (N-ary Trees)


Generic trees are a collection of nodes where each node is a data structure
that consists of records and a list of references to its children(duplicate…

5 min read

Count the Number of Binary Search Trees present in a Binary Tree


Given a binary tree, the task is to count the number of Binary Search Trees
present in it. Examples: Input: 1 / \ 2 3 / \ / \ 4 5 6 7 Output: 4Here each…

10 min read

Construct a Maximum Binary Tree from two given Binary Trees


Given two Binary Trees, the task is to create a Maximum Binary Tree from
the two given binary trees and print the Inorder Traversal of that tree.…

8 min read

Check if two Binary trees are identical after exactly K changes


Given two binary trees T1 and T2 and integer K, the task is to check
whether both trees are identical or not after making exactly K changes in…

9 min read

Foldable Binary Trees

https://www.geeksforgeeks.org/enumeration-of-binary-trees/?ref=lbp 4/8
3/30/25, 4:09 PM Enumeration of Binary Trees | GeeksforGeeks

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…

15+ min read

Merge Two Balanced Binary Search Trees


You are given two balanced binary search trees e.g., AVL or Red-Black
Tree. Write a function that merges the two given balanced BSTs into a…

15+ min read

Print Common Nodes in Two Binary Search Trees


Given two Binary Search Trees, find common nodes in them. In other
words, find the intersection of two BSTs. Example: Input: root1: 5 / \ 1 10…

15+ min read

Check if leaf traversal of two Binary Trees is same?


Leaf traversal is the sequence of leaves traversed from left to right. The
problem is to check if the leaf traversals of two given Binary Trees are…

15+ min read

Number of full binary trees such that each node is product of its…
Given an array of n integers, each integer is greater than 1. The task is to
find the number of Full binary tree from the given integers, such that eac…

11 min read

Corporate & Communications Address:


A-143, 7th Floor, Sovereign Corporate
Tower, Sector- 136, Noida, Uttar Pradesh
(201305)

Registered Address:
K 061, Tower K, Gulshan Vivante
Apartment, Sector 137, Noida, Gautam
https://www.geeksforgeeks.org/enumeration-of-binary-trees/?ref=lbp 5/8
3/30/25, 4:09 PM Enumeration of Binary Trees | GeeksforGeeks
Buddh Nagar, Uttar Pradesh, 201305

Advertise with us

Company Explore
About Us Job-A-Thon Hiring Challenge
Legal Hack-A-Thon
Privacy Policy GfG Weekly Contest
Careers Offline Classes (Delhi/NCR)
In Media DSA in JAVA/C++
Contact Us Master System Design
GfG Corporate Solution Master CP
Placement Training Program GeeksforGeeks Videos
Geeks Community

Languages DSA
Python Data Structures
Java Algorithms
C++ DSA for Beginners
PHP Basic DSA Problems
GoLang DSA Roadmap
SQL DSA Interview Questions
R Language Competitive Programming
Android Tutorial

Data Science & ML Web Technologies


Data Science With Python HTML
Data Science For Beginner CSS
Machine Learning JavaScript
ML Maths TypeScript
Data Visualisation ReactJS
Pandas NextJS
NumPy NodeJs
NLP Bootstrap
Deep Learning Tailwind CSS

Python Tutorial Computer Science


Python Programming Examples GATE CS Notes
Django Tutorial Operating Systems
Python Projects Computer Network
Python Tkinter Database Management System
Web Scraping Software Engineering
OpenCV Tutorial Digital Logic Design
https://www.geeksforgeeks.org/enumeration-of-binary-trees/?ref=lbp 6/8
3/30/25, 4:09 PM Enumeration of Binary Trees | GeeksforGeeks

Python Interview Question Engineering Maths

DevOps System Design


Git High Level Design
AWS Low Level Design
Docker UML Diagrams
Kubernetes Interview Guide
Azure Design Patterns
GCP OOAD
DevOps Roadmap System Design Bootcamp
Interview Questions

School Subjects Software and Tools


Mathematics AI Tools Directory
Physics Marketing Tools Directory
Chemistry Accounting Software Directory
Biology HR Management Tools
Social Science Editing Software Directory
English Grammar Microsoft Products and Apps
Figma Tutorial

Databases Preparation Corner


SQL Company-Wise Recruitment Process
MYSQL Resume Templates
PostgreSQL Aptitude Preparation
PL/SQL Puzzles
MongoDB Company-Wise Preparation
Companies
Colleges

Competitive Exams More Tutorials


JEE Advanced Software Development
UGC NET Software Testing
UPSC Product Management
SSC CGL Project Management
SBI PO Linux
SBI Clerk Excel
IBPS PO All Cheat Sheets
IBPS Clerk Recent Articles

Free Online Tools Write & Earn


Typing Test Write an Article
Image Editor Improve an Article
Code Formatters Pick Topics to Write
Code Converters Share your Experiences
Currency Converter Internships
Random Number Generator
Random Password Generator

DSA/Placements Development/Testing
https://www.geeksforgeeks.org/enumeration-of-binary-trees/?ref=lbp 7/8
3/30/25, 4:09 PM Enumeration of Binary Trees | GeeksforGeeks

DSA - Self Paced Course JavaScript Full Course


DSA in JavaScript - Self Paced Course React JS Course
DSA in Python - Self Paced React Native Course
C Programming Course Online - Learn C with Data Structures Django Web Development Course
Complete Interview Preparation Complete Bootstrap Course
Master Competitive Programming Full Stack Development - [LIVE]
Core CS Subject for Interview Preparation JAVA Backend Development - [LIVE]
Mastering System Design: LLD to HLD Complete Software Testing Course [LIVE]
Tech Interview 101 - From DSA to System Design [LIVE] Android Mastery with Kotlin [LIVE]
DSA to Development [HYBRID]
Placement Preparation Crash Course [LIVE]

Machine Learning/Data Science Programming Languages


Complete Machine Learning & Data Science Program - [LIVE] C Programming with Data Structures
Data Analytics Training using Excel, SQL, Python & PowerBI - C++ Programming Course
[LIVE] Java Programming Course
Data Science Training Program - [LIVE] Python Full Course
Mastering Generative AI and ChatGPT
Data Science Course with IBM Certification

Clouds/Devops GATE 2026


DevOps Engineering GATE CS Rank Booster
AWS Solutions Architect Certification GATE DA Rank Booster
Salesforce Certified Administrator Course GATE CS & IT Course - 2026
GATE DA Course 2026
GATE Rank Predictor

@GeeksforGeeks, Sanchhaya Education Private Limited, All rights reserved

https://www.geeksforgeeks.org/enumeration-of-binary-trees/?ref=lbp 8/8
3/30/25, 4:09 PM Types of Binary Tree | GeeksforGeeks

Types of Binary Tree


Last Updated : 05 Sep, 2023

We have discussed Introduction to Binary Tree in set 1 and the


Properties of Binary Tree in Set 2. In this post, common types of Binary
Trees are discussed.

Types of Binary Tree based on the number of


children:
Following are the types of Binary Tree based on the number of
children:

1. Full Binary Tree


2. Degenerate Binary Tree
3. Skewed Binary Trees

1. Full Binary Tree

A Binary Tree is a full binary tree if every node has 0 or 2 children.


The following are examples of a full binary tree. We can also say a full
binary tree is a binary tree in which all nodes except leaf nodes have
two children.

A full Binary tree is a special type of binary tree in which every parent
node/internal node has either two or no children. It is also known as a
proper binary tree.

https://www.geeksforgeeks.org/types-of-binary-tree/?ref=lbp 1/10
3/30/25, 4:09 PM Types of Binary Tree | GeeksforGeeks

Full Binary Tree

2. Degenerate (or pathological) tree

A Tree where every internal node has one child. Such trees are
performance-wise same as linked list. A degenerate or pathological
tree is a tree having a single child either left or right.

Degenerate (or pathological) tree

3. Skewed Binary Tree

A skewed binary tree is a pathological/degenerate tree in which the


tree is either dominated by the left nodes or the right nodes. Thus,

https://www.geeksforgeeks.org/types-of-binary-tree/?ref=lbp 2/10
3/30/25, 4:09 PM Types of Binary Tree | GeeksforGeeks

there are two types of skewed binary tree: left-skewed binary tree and
right-skewed binary tree.

Skewed Binary Tree

Refer to this article to read about more on Skewed Binary Tree

Types of Binary Tree On the basis of the completion


of levels:
1. Complete Binary Tree
2. Perfect Binary Tree
3. Balanced Binary Tree

1. Complete Binary Tree

A Binary Tree is a Complete Binary Tree if all the levels are


completely filled except possibly the last level and the last level has
all keys as left as possible.

A complete binary tree is just like a full binary tree, but with two major
differences:

Every level except the last level must be completely filled.


All the leaf elements must lean towards the left.
The last leaf element might not have a right sibling i.e. a complete
binary tree doesn’t have to be a full binary tree.

https://www.geeksforgeeks.org/types-of-binary-tree/?ref=lbp 3/10
3/30/25, 4:09 PM Types of Binary Tree | GeeksforGeeks

Complete Binary Tree

Refer to this article to read about more on Complete Tree

2. Perfect Binary Tree

A Binary tree is a Perfect Binary Tree in which all the internal nodes
have two children and all leaf nodes are at the same level.
The following are examples of Perfect Binary Trees.

A perfect binary tree is a type of binary tree in which every internal


node has exactly two child nodes and all the leaf nodes are at the
same level.

Perfect Binary Tree

https://www.geeksforgeeks.org/types-of-binary-tree/?ref=lbp 4/10
3/30/25, 4:09 PM Types of Binary Tree | GeeksforGeeks

In a Perfect Binary Tree, the number of leaf nodes is the number of


internal nodes plus 1

L = I + 1 Where L = Number of leaf nodes, I = Number of internal


nodes.

A Perfect Binary Tree of height h (where the height of the binary tree
is the number of edges in the longest path from the root node to any
leaf node in the tree, height of root node is 0) has 2h+1 – 1 node.
An example of a Perfect binary tree is ancestors in the family. Keep a
person at root, parents as children, parents of parents as their
children.

Refer to this article to read about more on Perfect Tree

3. Balanced Binary Tree

A binary tree is balanced if the height of the tree is O(Log n) where n is


the number of nodes. For Example, the AVL tree maintains O(Log n)
height by making sure that the difference between the heights of the
left and right subtrees is at most 1. Red-Black trees maintain O(Log n)
height by making sure that the number of Black nodes on every root to
leaf paths is the same and that there are no adjacent red nodes.
Balanced Binary Search trees are performance-wise good as they
provide O(log n) time for search, insert and delete.

Example of Balanced and Unbalanced Binary Tree

https://www.geeksforgeeks.org/types-of-binary-tree/?ref=lbp 5/10
3/30/25, 4:09 PM Types of Binary Tree | GeeksforGeeks

It is a type of binary tree in which the difference between the height of


the left and the right subtree for each node is either 0 or 1. In the
figure above, the root node having a value 0 is unbalanced with a
depth of 2 units.

Some Special Types of Trees:


On the basis of node values, the Binary Tree can be classified into the
following special types:

1. Binary Search Tree


2. AVL Tree
3. Red Black Tree
4. B Tree
5. B+ Tree
6. Segment Tree

Below Image Shows Important Special cases of binary Trees:

Binary Tree Special cases

1. Binary Search Tree

Binary Search Tree is a node-based binary tree data structure that has
the following properties:

The left subtree of a node contains only nodes with keys lesser than
the node’s key.

https://www.geeksforgeeks.org/types-of-binary-tree/?ref=lbp 6/10
3/30/25, 4:09 PM Types of Binary Tree | GeeksforGeeks

The right subtree of a node contains only nodes with keys greater
than the node’s key.
The left and right subtree each must also be a binary search tree.

Binary Search Tree

2. AVL Tree

AVL tree is a self-balancing Binary Search Tree (BST) where the


difference between heights of left and right subtrees cannot be more
than one for all nodes.

Example of AVL Tree shown below:


The below tree is AVL because the differences between the heights of
left and right subtrees for every node are less than or equal to 1

https://www.geeksforgeeks.org/types-of-binary-tree/?ref=lbp 7/10
3/30/25, 4:09 PM Types of Binary Tree | GeeksforGeeks

AVL Tree

3. Red Black Tree

A red-black tree is a kind of self-balancing binary search tree where


each node has an extra bit, and that bit is often interpreted as the color
(red or black). These colors are used to ensure that the tree remains
balanced during insertions and deletions. Although the balance of the
tree is not perfect, it is good enough to reduce the searching time and
maintain it around O(log n) time, where n is the total number of
elements in the tree. This tree was invented in 1972 by Rudolf Bayer.

Red Black Tree

4. B – Tree

A B-tree is a type of self-balancing tree data structure that allows


efficient access, insertion, and deletion of data items. B-trees are
commonly used in databases and file systems, where they can
efficiently store and retrieve large amounts of data. A B-tree is
characterized by a fixed maximum degree (or order), which determines
the maximum number of child nodes that a parent node can have. Each
node in a B-tree can have multiple child nodes and multiple keys, and
the keys are used to index and locate data items.

Refer to this article to read about more on B-Tree


https://www.geeksforgeeks.org/types-of-binary-tree/?ref=lbp 8/10
3/30/25, 4:09 PM Types of Binary Tree | GeeksforGeeks

5. B+ Tree

A B+ tree is a variation of the B-tree that is optimized for use in file


systems and databases. Like a B-tree, a B+ tree also has a fixed
maximum degree and allows efficient access, insertion, and deletion of
data items. However, in a B+ tree, all data items are stored in the leaf
nodes, while the internal nodes only contain keys for indexing and
locating the data items. This design allows for faster searches and
sequential access of the data items, as all the leaf nodes are linked
together in a linked list.

Refer to this article to read about more on B+ Tree

6. Segment Tree

In computer science, a Segment Tree, also known as a statistic tree, is


a tree data structure used for storing information about intervals, or
segments. It allows querying which of the stored segments contain a
given point. It is, in principle, a static structure; that is, it’s a structure
that cannot be modified once it’s built. A similar data structure is the
interval tree.

A segment tree for a set I of n intervals uses O(n log n) storage and
can be built in O(n log n) time. Segment trees support searching for all
the intervals that contain a query point in time O(log n + k), k being the
number of retrieved intervals or segments.

https://www.geeksforgeeks.org/types-of-binary-tree/?ref=lbp 9/10
3/30/25, 4:09 PM Types of Binary Tree | GeeksforGeeks

Segment Tree

Refer to this article to read about more on Segment Tree

https://www.geeksforgeeks.org/types-of-binary-tree/?ref=lbp 10/10
3/30/25, 4:10 PM Complete Binary Tree | GeeksforGeeks

Complete Binary Tree


Last Updated : 03 Sep, 2023

We know a tree is a non-linear data structure. It has no limitation on


the number of children. A binary tree has a limitation as any node of
the tree has at most two children: a left and a right child.

What is a Complete Binary Tree?


A complete binary tree is a special type of binary tree where all the
levels of the tree are filled completely except the lowest level nodes
which are filled from as left as possible.

Complete Binary Tree

Some terminology of Complete Binary Tree:


Root – Node in which no edge is coming from the parent. Example -
node A
Child – Node having some incoming edge is called child. Example –
nodes B, F are the child of A and C respectively.
Sibling – Nodes having the same parent are sibling. Example- D, E
are siblings as they have the same parent B.
Degree of a node – Number of children of a particular parent.
Example- Degree of A is 2 and Degree of C is 1. Degree of D is 0.
Internal/External nodes – Leaf nodes are external nodes and non
leaf nodes are internal nodes.
Level – Count nodes in a path to reach a destination node.
Example- Level of node D is 2 as nodes A and B form the path.

https://www.geeksforgeeks.org/complete-binary-tree/?ref=lbp 1/9
3/30/25, 4:10 PM Complete Binary Tree | GeeksforGeeks

Height – Number of edges to reach the destination node, Root is at


height 0. Example – Height of node E is 2 as it has two edges from
the root.

Properties of Complete Binary Tree:


A complete binary tree is said to be a proper binary tree where all
leaves have the same depth.
In a complete binary tree number of nodes at depth d is 2d.
In a complete binary tree with n nodes height of the tree is
log(n+1).
All the levels except the last level are completely full.

Perfect Binary Tree vs Complete Binary Tree:


A binary tree of height ‘h’ having the maximum number of nodes is a
perfect binary tree.
For a given height h, the maximum number of nodes is 2h+1-1.

A complete binary tree of height h is a perfect binary tree up to height


h-1, and in the last level element are stored in left to right order.

Example 1:

A Binary Tree

The height of the given binary tree is 2 and the maximum number of
nodes in that tree is n= 2h+1-1 = 22+1-1 = 23-1 = 7.
Hence we can conclude it is a perfect binary tree.
Now for a complete binary tree, It is full up to height h-1 i.e.; 1, and
the last level elements are stored in left to right order. Hence it is a
complete Binary tree also. Here is the representation of elements
when stored in an array

https://www.geeksforgeeks.org/complete-binary-tree/?ref=lbp 2/9
3/30/25, 4:10 PM Complete Binary Tree | GeeksforGeeks

Element stored in an array level by level

In the array, all the elements are stored continuously.

Example 2:

A binary tree

Height of the given binary tree is 2 and the maximum number of nodes
that should be there are 2h+1 – 1 = 22+1 – 1 = 23 – 1 = 7.
But the number of nodes in the tree is 6. Hence it is not a perfect
binary tree.
Now for a complete binary tree, It is full up to height h-1 i.e.; 1, and
the last level element are stored in left to right order. Hence this is a
complete binary tree. Store the element in an array and it will be like;

Element stored in an array level by level

Example 3:

A binary tree

https://www.geeksforgeeks.org/complete-binary-tree/?ref=lbp 3/9
3/30/25, 4:10 PM Complete Binary Tree | GeeksforGeeks

The height of the binary tree is 2 and the maximum number of nodes
that can be there is 7, but there are only 5 nodes hence it is not a
perfect binary tree.
In case of a complete binary tree, we see that in the last level
elements are not filled from left to right order. So it is not a complete
binary tree.

Element stored in an array level by level

The elements in the array are not continuous.

Full Binary Tree vs Complete Binary tree:


For a full binary tree, every node has either 2 children or 0 children.

Example 1:

A binary tree

In the given binary tree there is no node having degree 1, either 2 or 0


children for every node, hence it is a full binary tree.

For a complete binary tree, elements are stored in level by level and
not from the leftmost side in the last level. Hence this is not a
complete binary tree. The array representation is:

Element stored in an array level by level

Example 2:

https://www.geeksforgeeks.org/complete-binary-tree/?ref=lbp 4/9
3/30/25, 4:10 PM Complete Binary Tree | GeeksforGeeks

A binary Tree

In the given binary tree there is no node having degree 1. Every node
has a degree of either 2 or 0. Hence it is a full binary tree.

For a complete binary tree, elements are stored in a level by level


manner and filled from the leftmost side of the last level. Hence this a
complete binary tree. Below is the array representation of the tree:

Element stored in an array level by level

Example 3:

A binary tree

In the given binary tree node B has degree 1 which violates the
property of full binary tree hence it is not a full Binary tree

For a complete binary tree, elements are stored in level by level


manner and filled from the leftmost side of the last level. Hence this is
a complete binary tree. Array representation of the binary tree is:

https://www.geeksforgeeks.org/complete-binary-tree/?ref=lbp 5/9
3/30/25, 4:10 PM Complete Binary Tree | GeeksforGeeks

Element stored in an array level by level

Example 4:

a binary tree

In the given binary tree node C has degree 1 which violates the
property of a full binary tree hence it is not a full Binary tree

For a complete binary tree, elements are stored in level by level


manner and filled from the leftmost side of the last level. Here node E
violates the condition. Hence this is not a complete binary tree.

Creation of Complete Binary Tree:


We know a complete binary tree is a tree in which except for the last
level (say l)all the other level has (2l) nodes and the nodes are lined
up from left to right side.
It can be represented using an array. If the parent is it index i so the
left child is at 2i+1 and the right child is at 2i+2.

Complete binary tree and its array representation

Algorithm:

For the creation of a Complete Binary Tree, we require a queue data


structure to keep track of the inserted nodes.
https://www.geeksforgeeks.org/complete-binary-tree/?ref=lbp 6/9
3/30/25, 4:10 PM Complete Binary Tree | GeeksforGeeks

Step 1: Initialize the root with a new node when the tree is empty.

Step 2: If the tree is not empty then get the front element

If the front element does not have a left child then set the left child
to a new node
If the right child is not present set the right child as a new node

Step 3: If the node has both the children then pop it from the queue.

Step 4: Enqueue the new data.

Illustration:

Consider the below array:

1. The 1st element will the root (value at index = 0)

A is taken as root

2. The next element (at index = 1) will be left and third element
(index = 2) will be right child of root

B as left child and D as right child

3. fourth (index = 3) and fifth element (index = 4) will be the left


and right child of B node

https://www.geeksforgeeks.org/complete-binary-tree/?ref=lbp 7/9
3/30/25, 4:10 PM Complete Binary Tree | GeeksforGeeks

E and F are left and right child of B

4. Next element (index = 5) will be left child of the node D

G is made left child of D node

This is how complete binary tree is created.

Implementation: For the implementation of building a Complete


Binary Tree from level order traversal is given in this post.

Application of the Complete binary tree:


Heap Sort
Heap sort-based data structure

Check if a given binary tree is complete or not: Follow this post to


check if the given binary tree is complete or not.

https://www.geeksforgeeks.org/complete-binary-tree/?ref=lbp 8/9
3/30/25, 4:10 PM Complete Binary Tree | GeeksforGeeks

https://www.geeksforgeeks.org/complete-binary-tree/?ref=lbp 9/9
3/30/25, 4:10 PM Perfect Binary Tree | GeeksforGeeks

Perfect Binary Tree


Last Updated : 11 Jan, 2023

What is a Perfect Binary Tree?

A perfect binary tree is a special type of binary tree in which all the
leaf nodes are at the same depth, and all non-leaf nodes have two
children. In simple terms, this means that all leaf nodes are at the
maximum depth of the tree, and the tree is completely filled with no
gaps.

The maximum number of nodes in a perfect binary tree is given by the


formula 2^(d+1) – 1, where d is the depth of the tree. This means that
a perfect binary tree with a depth of n has 2^n leaf nodes and a total
of 2^(n+1) – 1 nodes.

Perfect binary trees have a number of useful properties that make


them useful in various applications. For example, they are often used
in the implementation of heap data structures, as well as in the
construction of threaded binary trees. They are also used in the
implementation of algorithms such as heapsort and merge sort.

In other words, it can be said that each level of the tree is completely
filled by the nodes.

Examples of Perfect Binary Tree:

https://www.geeksforgeeks.org/perfect-binary-tree/?ref=lbp 1/4
3/30/25, 4:10 PM Perfect Binary Tree | GeeksforGeeks

Example of a Perfect Binary Tree

A tree with only the root node is also a perfect binary tree.

Example-2

The following tree is not a perfect binary tree because the last level of
the tree is not completely filled.

Not a Perfect Binary Tree

Properties of a Perfect Binary Tree:

Degree: The degree of a node of a tree is defined as the number of


children of that node. All the internal nodes have a degree of 2. The
https://www.geeksforgeeks.org/perfect-binary-tree/?ref=lbp 2/4
3/30/25, 4:10 PM Perfect Binary Tree | GeeksforGeeks

leaf nodes of a perfect binary tree have a degree of 0.


Number of leaf nodes: If the height of the perfect binary tree is h,
then the number of leaf nodes will be 2h because the last level is
completely filled.
Depth of a node: Average depth of a node in a perfect binary tree is
Θ(ln(n)).
Relation between leaf nodes and non-leaf nodes: No. of leaf
nodes = No. of non-leaf nodes +1.
Total number of nodes: A tree of height h has total nodes = 2h+1 –
1. Each node of the tree is filled. So total number of nodes can be
calculated as 20 + 21 + . . . + 2h = 2h+1 – 1.
Height of the tree: The height of a perfect binary tree with N
number of nodes = log(N + 1) – 1 = Θ(ln(n)). This can be calculated
using the relation shown while calculating the total number of
nodes in a perfect binary tree.

Check whether a tree is a Perfect Binary Tree or not:

Check the depth of the tree. A perfect binary tree is defined as a


tree where all leaf nodes are at the same depth, and all non-leaf
nodes have two children. To check whether a tree is a perfect binary
tree, you can first calculate the depth of the tree.
Check the number of nodes at each level: Once you have calculated
the depth of the tree, you can then check the number of nodes at
each level. In a perfect binary tree, the number of nodes at each
level should be a power of 2 (e.g. 1, 2, 4, 8, etc.). If any level has a
different number of nodes, the tree is not a perfect binary tree.

For more information about this refer to the article article: Check
whether a given binary tree is perfect or not

Summary:
All leaf nodes are at the same depth. In a perfect binary tree, all
leaf nodes are at the maximum depth of the tree. This means that
the tree is completely filled with no gaps.

https://www.geeksforgeeks.org/perfect-binary-tree/?ref=lbp 3/4
3/30/25, 4:10 PM Perfect Binary Tree | GeeksforGeeks

All non-leaf nodes have two children. In a perfect binary tree, all
non-leaf nodes have exactly two children. This means that the tree
has a regular structure, with all nodes having either two children or
no children.
The maximum number of nodes is given by a formula: The
maximum number of nodes in a perfect binary tree is given by the
formula 2^(d+1) – 1, where d is the depth of the tree.
They have a symmetrical structure. This is because all non-leaf
nodes have two children, perfect binary trees have a symmetrical
structure.
They can be represented using an array. Perfect binary trees can be
represented using an array, where the left child of a node at index i
is stored at index 2i+1 and the right child is stored at index 2i+2.
This makes it easy to access the children of a node and to traverse
the tree.

https://www.geeksforgeeks.org/perfect-binary-tree/?ref=lbp 4/4
3/30/25, 4:10 PM Level Order Traversal (Breadth First Search or BFS) of Binary Tree | GeeksforGeeks

Level Order Traversal (Breadth First Search or


BFS) of Binary Tree
Last Updated : 25 Mar, 2025

Given a Binary Tree, the task is to find its Level Order Traversal. 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: [[5], [12, 13], [7, 14, 2], [17, 23, 27, 3, 8, 11]]
Explanation: Level 0: Start with the root → [5]
Level 1: Visit its children → [12, 13]
Level 2: Visit children of 3 and 2 → [7, 14, 2]
Level 3: Visit children of 4 and 5 → [17, 23, 27, 3, 8, 11]

Table of Content
How does Level Order Traversal work?
[Naive Approach] Using Recursion – O(n) time and O(n) space
https://www.geeksforgeeks.org/level-order-tree-traversal/?ref=lbp 1/6
3/30/25, 4:10 PM Level Order Traversal (Breadth First Search or BFS) of Binary Tree | GeeksforGeeks

[Expected Approach] Using Queue (Iterative) – O(n) time and O(n)


space

How does Level Order Traversal work?

Level Order Traversal visits all nodes at a lower level before moving to
a higher level. It can be implemented using:

Recursion
Queue (Iterative)

[Naive Approach] Using Recursion – O(n) time and O(n) space

The idea is to traverse the tree recursively, passing the current


node and its level, starting with the root at level 0. For each
visited node, its value is added to the result array, by considering
the value of current level as an index in the result array.

C++ Java Python C# JavaScript

class Node {
constructor(value) {
this.data = value;
this.left = null;
this.right = null;
}
}

function levelOrderRec(root, level, res) {


// Base case: If node is null, return
if (root === null) return;

// Add a new level to the result if needed


if (res.length <= level)
res.push([]);

// Add current node's data to its corresponding level


res[level].push(root.data);

// Recur for left and right children


levelOrderRec(root.left, level + 1, res);
levelOrderRec(root.right, level + 1, res);
}

// Function to perform level order traversal


function levelOrder(root) {
// Stores the result level by level

https://www.geeksforgeeks.org/level-order-tree-traversal/?ref=lbp 2/6
3/30/25, 4:10 PM Level Order Traversal (Breadth First Search or BFS) of Binary Tree | GeeksforGeeks
const res = [];

levelOrderRec(root, 0, res);
return res;
}

// 5
// / \
// 12 13
// / \ \
// 7 14 2
// / \ / \ / \
//17 23 27 3 8 11

const root = new Node(5);


root.left = new Node(12);
root.right = new Node(13);

root.left.left = new Node(7);


root.left.right = new Node(14);

root.right.right = new Node(2);

root.left.left.left = new Node(17);


root.left.left.right = new Node(23);

root.left.right.left = new Node(27);


root.left.right.right = new Node(3);

root.right.right.left = new Node(8);


root.right.right.right = new Node(11);

const res = levelOrder(root);

for (const level of res) {


process.stdout.write("[");
for (let i = 0; i < level.length; i++) {
process.stdout.write(level[i].toString());
if (i < level.length - 1) process.stdout.write(", ");
}
process.stdout.write("] ");
}

Output

[5] [12, 13] [7, 14, 2] [17, 23, 27, 3, 8, 11]

[Expected Approach] Using Queue (Iterative) – O(n) time and


O(n) space

Looking at the examples, it’s clear that tree nodes need to be


traversed level by level from top to bottom. Since the tree

https://www.geeksforgeeks.org/level-order-tree-traversal/?ref=lbp 3/6
3/30/25, 4:10 PM Level Order Traversal (Breadth First Search or BFS) of Binary Tree | GeeksforGeeks

structure allows us to access nodes starting from the root and


moving downward, this process naturally follows a First-In-
First-Out (FIFO) order. So we can use queue data structure to
perform level order traversal.

1/8

C++ Java Python C# JavaScript

class Node {
constructor(value) {
this.data = value;
this.left = null;
this.right = null;
}
}

// Iterative method to perform level order traversal


function levelOrder(root) {
if (root === null)
return [];

// Create an empty queue for level order traversal


let q = [];
let res = [];

// Enqueue Root
q.push(root);
let currLevel = 0;

while (q.length > 0) {


let len = q.length;
res.push([]);

for (let i = 0; i < len; i++) {


// Add front of queue and remove it from queue
let node = q.shift();
https://www.geeksforgeeks.org/level-order-tree-traversal/?ref=lbp 4/6
3/30/25, 4:10 PM Level Order Traversal (Breadth First Search or BFS) of Binary Tree | GeeksforGeeks
res[currLevel].push(node.data);

// Enqueue left child


if (node.left !== null)
q.push(node.left);

// Enqueue right child


if (node.right !== null)
q.push(node.right);
}
currLevel++;
}
return res;
}

// 5
// / \
// 12 13
// / \ \
// 7 14 2
// / \ / \ / \
//17 23 27 3 8 11

const root = new Node(5);


root.left = new Node(12);
root.right = new Node(13);

root.left.left = new Node(7);


root.left.right = new Node(14);

root.right.right = new Node(2);

root.left.left.left = new Node(17);


root.left.left.right = new Node(23);

root.left.right.left = new Node(27);


root.left.right.right = new Node(3);

root.right.right.left = new Node(8);


root.right.right.right = new Node(11);

// Perform level order traversal and get the result


const res = levelOrder(root);

// Print the result in the required format


for (const level of res) {
process.stdout.write('[');
process.stdout.write(level.join(', '));
process.stdout.write('] ');
}

Output

[5] [12, 13] [7, 14, 2] [17, 23, 27, 3, 8, 11]

https://www.geeksforgeeks.org/level-order-tree-traversal/?ref=lbp 5/6
3/30/25, 4:10 PM Level Order Traversal (Breadth First Search or BFS) of Binary Tree | GeeksforGeeks

Problems Based on Level Order Traversal

Print level order traversal line by line


Connect nodes at same level
ZigZag Tree Traversal

https://www.geeksforgeeks.org/level-order-tree-traversal/?ref=lbp 6/6
3/30/25, 4:10 PM Level order traversal in spiral form | GeeksforGeeks

Level order traversal in spiral form


Last Updated : 17 Sep, 2024

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 7
Explanation:
Level 1: 1
Level 2: 2 3
Level 3: 7 6 5 4
Nodes are traversed in the alternate order from front or back in
adjacent levels , so the output is 1 2 3 4 5 6 7.

Level order traversal of Binary Tree in Spiral form


Using Recursion:
The idea is to first calculate the height of the tree, then
recursively traverse each level and print the level order traversal
according to the current level.

Follow the below steps to Implement the idea:

https://www.geeksforgeeks.org/level-order-traversal-in-spiral-form/?ref=lbp 1/10
3/30/25, 4:10 PM Level order traversal in spiral form | GeeksforGeeks

Initialize a variable h to store the height of the binary tree.


Initialize a variable i, and ltr = false.
Traverse a loop from 1 till h:
Print the level order traversal of given traversal using
below recursive function:
printGivenLevel(tree, level, ltr)
if tree is NULL then return;
if level is 1, then
print(tree->data);
else if level greater than 1, then
if(ltr)
printGivenLevel(tree-
>left, level-1, ltr);
printGivenLevel(tree-
>right, level-1, ltr);
else
printGivenLevel(tree-
>right, level-1, ltr);
printGivenLevel(tree-
>left, level-1, ltr);
Update ltr = !ltr

Following is the implementation of the above approach.

C++ C Java Python C# JavaScript

<script>

// JavaScript program for recursive


// level order traversal in spiral form

class Node
{
constructor(d) {
this.left = null;
this.right = null;
this.data = d;
}
}

https://www.geeksforgeeks.org/level-order-traversal-in-spiral-form/?ref=lbp 2/10
3/30/25, 4:10 PM Level order traversal in spiral form | GeeksforGeeks
let root;

// Function to print the spiral traversal of tree


function printSpiral(node)
{
let h = height(node);
let i;

/* ltr -> left to right. If this variable is set then the


given label is traversed from left to right */
let ltr = false;
for (i = 1; i <= h; i++) {
printGivenLevel(node, i, ltr);

/*Revert ltr to traverse next level in opposite order*/


ltr = !ltr;
}
}

/* Compute the "height" of a tree -- the number of


nodes along the longest path from the root node
down to the farthest leaf node.*/
function height(node)
{
if (node == null)
return 0;
else {

/* compute the height of each subtree */


let lheight = height(node.left);
let rheight = height(node.right);

/* use the larger one */


if (lheight > rheight)
return (lheight + 1);
else
return (rheight + 1);
}
}

/* Print nodes at a given level */


function printGivenLevel(node, level, ltr)
{
if (node == null)
return;
if (level == 1)
document.write(node.data + " ");
else if (level > 1) {
if (ltr != false) {
printGivenLevel(node.left, level - 1, ltr);
printGivenLevel(node.right, level - 1, ltr);
}
else {
printGivenLevel(node.right, level - 1, ltr);
printGivenLevel(node.left, level - 1, ltr);
}
}
}

https://www.geeksforgeeks.org/level-order-traversal-in-spiral-form/?ref=lbp 3/10
3/30/25, 4:10 PM Level order traversal in spiral form | GeeksforGeeks
root = new Node(1);
root.left = new Node(2);
root.right = new Node(3);
root.left.left = new Node(7);
root.left.right = new Node(6);
root.right.left = new Node(5);
root.right.right = new Node(4);
document.write("Spiral order traversal of Binary Tree is " +
"</br>");
printSpiral(root);

</script>

Output

Spiral Order traversal of binary tree is


1 2 3 4 5 6 7

Time Complexity: O(N2), where N is the number of nodes in the given


tree.
Auxiliary Space: O(N), for recursive stack space.

Level order traversal of Binary Tree in Spiral form


Using Stack:
The idea is to use two separate stacks to store the level order
traversal as per their levels in adjacent order.

Follow the below steps to Implement the idea:

Initialize two stacks s1 and s2


Push the root of tree in s1
Initialize a while loop till either s1 or s2 is non-empty
Initialize a nested while loop till s1 contains nodes
Initialize temp = s1.top()
Pop the node from s1
Print temp -> data
If temp -> right is not NULL
Insert temp -> right in s2
If temp -> left is not NULL

https://www.geeksforgeeks.org/level-order-traversal-in-spiral-form/?ref=lbp 4/10
3/30/25, 4:10 PM Level order traversal in spiral form | GeeksforGeeks

Insert temp -> left in s2


Initialize a nested while loop till s2 contains nodes
Initialize temp = s2.top()
Pop the node from s2
Print temp -> data
If temp -> left is not NULL
Insert temp -> left in s1
If temp -> right is not NULL
Insert temp -> right in s1

Below is the implementation of the above approach:

C++ Java Python C# JavaScript

<script>
// Javascript implementation of an O(n) approach of
// level order traversal in spiral form

// A Binary Tree node


class Node
{
constructor(item) {
this.left = null;
this.right = null;
this.data = item;
}
}

let root;

function printSpiral(node)
{
if (node == null) {
return; // NULL check
}

// Create two stacks to store alternate levels


let s1 = []; // For levels to be printed
// from right to left
let s2 = []; // For levels to be printed
// from left to right

// Push first level to first stack 's1'


s1.push(node);

// Keep printing while any of the


// stacks has some nodes
while (s1.length > 0 || s2.length > 0) {
// Print nodes of current level from
// s1 and push nodes of next level to s2
https://www.geeksforgeeks.org/level-order-traversal-in-spiral-form/?ref=lbp 5/10
3/30/25, 4:10 PM Level order traversal in spiral form | GeeksforGeeks
while (s1.length > 0) {
let temp = s1[s1.length - 1];
s1.pop();
document.write(temp.data + " ");

// Note that is right is pushed before left


if (temp.right != null) {
s2.push(temp.right);
}

if (temp.left != null) {
s2.push(temp.left);
}
}

// Print nodes of current level from s2


// and push nodes of next level to s1
while (s2.length > 0) {
let temp = s2[s2.length - 1];
s2.pop();
document.write(temp.data + " ");

// Note that is left is pushed before right


if (temp.left != null) {
s1.push(temp.left);
}
if (temp.right != null) {
s1.push(temp.right);
}
}
}
}

root = new Node(1);


root.left = new Node(2);
root.right = new Node(3);
root.left.left = new Node(7);
root.left.right = new Node(6);
root.right.left = new Node(5);
root.right.right = new Node(4);
document.write("Spiral Order traversal of Binary Tree is " + "
</br>");
printSpiral(root);

// Thiscode is contributed by decode2207.


</script>

Output

Spiral Order traversal of binary tree is


1 2 3 4 5 6 7

Time Complexity: O(N), where N is the number of nodes in the binary


tree.

https://www.geeksforgeeks.org/level-order-traversal-in-spiral-form/?ref=lbp 6/10
3/30/25, 4:10 PM Level order traversal in spiral form | GeeksforGeeks

Auxiliary Space: O(N), for storing the nodes in the stack.

Level order traversal of Binary Tree in Spiral form


Using Deque:

The idea is to use Doubly Ended Queues, then push and pop the
nodes from each end in alternate order.

Follow the below steps to Implement the idea:

Initialize a deque dq.


Push root of the binary tree in dq
Initialize a variable reverse = true
Initialize a loop while dq is not empty:
Initialize n = dq.size()
IF reverse == false:
Initialize a nested loop while n > 0:
Decrement n by 1
If dq.front()->left is not NULL
Push dq.front()->left at the
back of Deque
If dq.front()->right is not NULL
Push dq.front()->right at the
back of Deque
Print dq.front()->key
Pop the node from front of the Deque
Update reverse = !reverse
Else
Initialize a nested loop while n > 0:
Decrement n by 1
If dq.back()->right is not NULL
Push dq.front()->right to the
front of Deque

https://www.geeksforgeeks.org/level-order-traversal-in-spiral-form/?ref=lbp 7/10
3/30/25, 4:10 PM Level order traversal in spiral form | GeeksforGeeks

If dq.back()->left is not NULL


Push dq.front()->left to the
front of Deque
Print dq.back()->key
Pop the node from back of the Deque
Update reverse = !reverse

Below is the implementation of the above approach:

C++ Java Python C# JavaScript

// Javascript implementation of an O(n) approach of


// level order traversal in spiral form

// A Binary Tree node


class Node
{
constructor(item) {
this.left = null;
this.right = null;
this.data = item;
}
}

let root;

function printSpiral(node)
{
if (node == null) {
return; // NULL check
}

// Create two stacks to store alternate levels


let s1 = []; // For levels to be printed
// from right to left
let s2 = []; // For levels to be printed
// from left to right

// Push first level to first stack 's1'


s1.push(node);

// Keep printing while any of the


// stacks has some nodes
while (s1.length > 0 || s2.length > 0) {
// Print nodes of current level from
// s1 and push nodes of next level to s2
while (s1.length > 0) {
let temp = s1[s1.length - 1];
s1.pop();
document.write(temp.data + " ");

// Note that is right is pushed before left

https://www.geeksforgeeks.org/level-order-traversal-in-spiral-form/?ref=lbp 8/10
3/30/25, 4:10 PM Level order traversal in spiral form | GeeksforGeeks
if (temp.right != null) {
s2.push(temp.right);
}

if (temp.left != null) {
s2.push(temp.left);
}
}

// Print nodes of current level from s2


// and push nodes of next level to s1
while (s2.length > 0) {
let temp = s2[s2.length - 1];
s2.pop();
document.write(temp.data + " ");

// Note that is left is pushed before right


if (temp.left != null) {
s1.push(temp.left);
}
if (temp.right != null) {
s1.push(temp.right);
}
}
}
}

root = new Node(1);


root.left = new Node(2);
root.right = new Node(3);
root.left.left = new Node(7);
root.left.right = new Node(6);
root.right.left = new Node(5);
root.right.right = new Node(4);
document.write("Spiral Order traversal of Binary Tree is " + "
</br>");
printSpiral(root);

Output

Spiral Order Traversal Of The Tree Is :


1 2 3 4 5 6 7

Time Complexity: O(N), where N is the number of nodes in the binary


tree.
Auxiliary Space: O(N), for storing the nodes in the Deque.

Please write comments if you find any bug in the above


program/algorithm; or if you want to share more information about
spiral traversal.

https://www.geeksforgeeks.org/level-order-traversal-in-spiral-form/?ref=lbp 9/10
3/30/25, 4:10 PM Level order traversal in spiral form | GeeksforGeeks

https://www.geeksforgeeks.org/level-order-traversal-in-spiral-form/?ref=lbp 10/10
3/30/25, 4:11 PM Reverse Level Order Traversal | GeeksforGeeks

Reverse Level Order Traversal


Last Updated : 17 Sep, 2024

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:
45
23
1

Table of Content
[Naive Approach] Using Recursion – O(n^2) Time and O(h) Space
[Expected Approach] Using Stack and Queue – O(n) Time and O(n)
Space
[Alternate Approach] Using a hash map – O(n) Time and O(n) Space

https://www.geeksforgeeks.org/reverse-level-order-traversal/?ref=lbp 1/7
3/30/25, 4:11 PM Reverse Level Order Traversal | GeeksforGeeks

[Naive Approach] Using Recursion – O(n^2) Time and O(h)


Space:

The algorithm for reverse level order traversal involves printing


nodes level by level, starting from the bottom-most level and
moving up to the root. First, the height of the tree is determined,
denoted as h. The traversal then begins from level h and
proceeds upwards to level 1. In each iteration, printGivenLevel
function is called to print nodes at the current level. It prints the
node’s data if the current level matches the required level. If not,
the function recursively explores the left and right subtrees to
find and print nodes at the required level.

C++ C Java Python C# JavaScript

// A recursive Javascript program to print


// reverse level order traversal

class Node {
constructor(x) {
this.data = x;
this.left = null;
this.right = null;
}
}

// Function to find the height of the tree.


function height(node) {
if (node === null)
return 0;

let lheight = height(node.left);


let rheight = height(node.right);

return Math.max(lheight, rheight) + 1;


}

// Print nodes at a given level


function printGivenLevel(root, nodeLevel, reqLevel) {
if (root === null)
return;

// if the required level is reached, print the node.


if (nodeLevel === reqLevel)
console.log(root.data);

// else call function for left and right subtree.


else if (nodeLevel < reqLevel) {
printGivenLevel(root.left, nodeLevel + 1, reqLevel);
printGivenLevel(root.right, nodeLevel + 1, reqLevel);
}
https://www.geeksforgeeks.org/reverse-level-order-traversal/?ref=lbp 2/7
3/30/25, 4:11 PM Reverse Level Order Traversal | GeeksforGeeks
}

// Function to print REVERSE level order traversal of a tree


function reverseLevelOrder(root) {

// find the height of the tree.


let h = height(root);

// Start printing from the lowest level.


for (let i = h; i >= 1; i--)
printGivenLevel(root, 1, i);
}

// create hard coded tree


// 1
// / \
// 2 3
// / \
// 4 5
let root = new Node(1);
root.left = new Node(2);
root.right = new Node(3);
root.left.left = new Node(4);
root.left.right = new Node(5);

reverseLevelOrder(root);

Output

4 5 2 3 1

Time Complexity: O(n^2)


Auxiliary Space: O(h), where h is the height of the tree.

[Expected Approach] Using Stack and Queue – O(n) Time and


O(n) Space:

The approach for reverse level order traversal, using a stack


and queue is conceptually similar to a standard level order
traversal but with key modifications. Instead of printing each
node as it is visited, the nodes are pushed onto a stack.
Additionally, when enqueueing children nodes, the right child is
enqueued before the left child. This ensures that when nodes
are popped from the stack, they are printed in reverse level
order.

https://www.geeksforgeeks.org/reverse-level-order-traversal/?ref=lbp 3/7
3/30/25, 4:11 PM Reverse Level Order Traversal | GeeksforGeeks

Step by step implementation:

1. The idea is to use a stack to get the reverse level order.


2. Push the root node into a queue. While queue is not empty,
perform steps 3,4.
3. Pop the front element of the queue. Instead of printing it (like in
level order), push node’s value into a stack. This way the elements
present on upper levels will be printed later than elements on
lower levels.
4. If the right child of current node exists, push it into queue before
left child. This is because elements on the same level should be
printed from left to right.
5. While stack is not empty, pop the top element and print it.

C++ Java Python C# JavaScript

// Javascript program to print reverse level


// order traversal using stack and queue

class Node {
constructor(x) {
this.data = x;
this.left = null;
this.right = null;
}
}

// Function to print REVERSE level order traversal of a tree


function reverseLevelOrder(root) {
let S = [];
let Q = [];
Q.push(root);

while (Q.length > 0) {

// Dequeue node
let curr = Q.shift();
S.push(curr);

// Enqueue right child


if (curr.right)
Q.push(curr.right);

// Enqueue left child


if (curr.left)
Q.push(curr.left);
}

// pop all items from stack one by one and print them
while (S.length > 0) {
https://www.geeksforgeeks.org/reverse-level-order-traversal/?ref=lbp 4/7
3/30/25, 4:11 PM Reverse Level Order Traversal | GeeksforGeeks
let curr = S.pop();
console.log(curr.data);
}
}

// create hard coded tree


// 1
// / \
// 2 3
// / \
// 4 5
let root = new Node(1);
root.left = new Node(2);
root.right = new Node(3);
root.left.left = new Node(4);
root.left.right = new Node(5);

reverseLevelOrder(root);

Output

4 5 2 3 1

Time Complexity: O(n), where n is the number of nodes in the binary


tree.
Auxiliary Space: O(n)

[Alternate Approach] Using a hash map – O(n) Time and O(n)


Space:

The approach to reverse level order traversal using a hash map


involves storing nodes by their levels and then retrieving them in
reverse order. To achieve this, a hash map is used where each
level of the binary tree maps to a list of nodes at that level.
During a pre-order traversal of the tree, nodes are added to the
hash map based on their level, ensuring that nodes are
processed from the leftmost node at each level first. If the
current node is null, the function returns immediately. Otherwise,
it adds the node to the list corresponding to its level in the hash
map, then recursively processes the left and right children.

After completing the traversal, the height of the tree, denoted by


the size of the hash map, determines the number of levels. The
final step is to iterate over the hash map from the highest level
down to level 1, printing nodes from each level to achieve the
reverse level order traversal.
https://www.geeksforgeeks.org/reverse-level-order-traversal/?ref=lbp 5/7
3/30/25, 4:11 PM Reverse Level Order Traversal | GeeksforGeeks

Below is the implementation of the above approach:

C++ Java Python C# JavaScript

// JavaScript program to print REVERSE level


// order traversal using hashmap
class Node {
constructor(x) {
this.data = x;
this.left = null;
this.right = null;
}
}

// Recursive function to traverse the binary tree


// and add nodes to the hashmap
function addNodesToMap(node, level, map) {
if (node === null) return;

if (!map.has(level)) map.set(level, []);


map.get(level).push(node.data);

// Recursively traverse the left and right subtrees


addNodesToMap(node.left, level + 1, map);
addNodesToMap(node.right, level + 1, map);
}

function reverseLevelOrder(root) {
const result = [];
const map = new Map();

// Traverse the binary tree recursively


// and add nodes to the hashmap
addNodesToMap(root, 0, map);

// Iterate over the hashmap in reverse order


// of the levels and add nodes to the result
for (let level = map.size - 1; level >= 0; level--) {
result.push(...map.get(level));
}

return result;
}

function printList(list) {
console.log(list.join(" "));
}

const root = new Node(1);


root.left = new Node(2);
root.right = new Node(3);
root.left.left = new Node(4);
root.left.right = new Node(5);

https://www.geeksforgeeks.org/reverse-level-order-traversal/?ref=lbp 6/7
3/30/25, 4:11 PM Reverse Level Order Traversal | GeeksforGeeks
const result = reverseLevelOrder(root);
printList(result);

Output

4 5 2 3 1

Time complexity: O(n), where n is the number of nodes in the binary


tree.
Auxiliary Space: O(n)

https://www.geeksforgeeks.org/reverse-level-order-traversal/?ref=lbp 7/7
3/30/25, 4:11 PM BFS vs DFS for Binary Tree | GeeksforGeeks

BFS vs DFS for Binary Tree


Last Updated : 19 Feb, 2024

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:

1. Breadth First Traversal (Or Level Order Traversal)


2. Depth First Traversals
Inorder Traversal (Left-Root-Right)
Preorder Traversal (Root-Left-Right)
Postorder Traversal (Left-Right-Root)

BFS vs DFS for Binary Tree

What is Breadth First Search?


Breadth First Search (BFS) is a graph traversal algorithm that starts
traversing the graph from the root node and explores all the
neighboring nodes at the present depth prior to moving on to the
nodes at the next depth level.
https://www.geeksforgeeks.org/bfs-vs-dfs-binary-tree/?ref=lbp 1/4
3/30/25, 4:11 PM BFS vs DFS for Binary Tree | GeeksforGeeks

How does BFS Tree Traversal work?


Breadth First Search (BFS) traversal explores all the neighboring
nodes at the present depth prior to moving on to the nodes at the next
depth level. In the context of a tree, BFS traversal works similarly.

Here’s how BFS tree traversal typically works:

1. Start at the root node and add it to a queue.


2. While the queue is not empty, dequeue a node and visit it.
3. Enqueue all of its children (if any) into the queue.
4. Repeat steps 2 and 3 until the queue is empty.

This approach ensures that nodes are visited level by level, moving
horizontally across the tree before moving to the next level. This way,
BFS explores the nodes in a breadth-first manner, making it useful for
tasks like finding the shortest path in unweighted graphs or trees.

What is a Depth-first search?


DFS (Depth-first search) is a technique used for traversing trees or
graphs. Here backtracking is used for traversal. In this traversal first,
the deepest node is visited and then backtracks to its parent node if no
sibling of that node exists

1. Inorder Traversal (Practice):

Follow the below steps to solve the problem:

Traverse the left subtree, i.e., call Inorder(left-subtree)


Visit the root
Traverse the right subtree, i.e., call Inorder(right-subtree)

2. Preorder Traversal (Practice):

Follow the below steps to solve the problem:

Visit the root


Traverse the left subtree, i.e., call Preorder(left-subtree)
Traverse the right subtree, i.e., call Preorder(right-subtree)

https://www.geeksforgeeks.org/bfs-vs-dfs-binary-tree/?ref=lbp 2/4
3/30/25, 4:11 PM BFS vs DFS for Binary Tree | GeeksforGeeks

3. Postorder Traversal (Practice):

Follow the below steps to solve the problem:

Traverse the left subtree, i.e., call Postorder(left-subtree)


Traverse the right subtree, i.e., call Postorder(right-subtree)
Visit the root.

Difference Between BFS and DFS:

Parameters BFS DFS

Stands for BFS stands for Breadth DFS stands for Depth First
First Search. Search.

Data BFS(Breadth First


Structure Search) uses Queue
DFS(Depth First Search) uses
data structure for
Stack data structure.
finding the shortest
path.

Definition DFS is also a traversal


BFS is a traversal
approach in which the
approach in which we
traverse begins at the root
first walk through all
node and proceeds through
nodes on the same
the nodes as far as possible
level before moving on
until we reach the node with
to the next level.
no unvisited nearby nodes.

Conceptual BFS builds the tree DFS builds the tree sub-tree
Difference level by level. by sub-tree.

Approach It works on the concept


It works on the concept of
used of FIFO (First In First
LIFO (Last In First Out).
Out).

Suitable for BFS is more suitable DFS is more suitable when


for searching vertices there are solutions away
https://www.geeksforgeeks.org/bfs-vs-dfs-binary-tree/?ref=lbp 3/4
3/30/25, 4:11 PM BFS vs DFS for Binary Tree | GeeksforGeeks

Parameters BFS DFS

closer to the given from source.


source.

Applications BFS is used in various DFS is used in various


applications such as applications such as acyclic
bipartite graphs, graphs and finding strongly
shortest paths, etc. connected components etc.

Conclusion
BFS and DFS are both efficient algorithms for traversing binary trees.
The choice of which algorithm to use depends on the specific
application and the desired traversal order. BFS is preferred when the
goal is to visit all nodes at the same level, while DFS is preferred
when exploring a branch as far as possible is more important.

https://www.geeksforgeeks.org/bfs-vs-dfs-binary-tree/?ref=lbp 4/4
3/30/25, 4:11 PM Morris traversal for Preorder | GeeksforGeeks

Morris traversal for Preorder


Last Updated : 04 Nov, 2024

Given a Binary Tree, the task is to print its Preorder Traversal, without
using recursion or stack.

Examples:

Input:

Output: 1 2 4 5 3
Explanation: Preorder traversal (Root->Left->Right) of the tree
is 1 2 4 5 3

Input:

https://www.geeksforgeeks.org/morris-traversal-for-preorder/?ref=lbp 1/4
3/30/25, 4:11 PM Morris traversal for Preorder | GeeksforGeeks

Output: 8 1 7 10 5 10 6 6
Explanation: Preorder traversal (Root->Left->Right) of the tree
is 8 1 7 10 5 10 6 6

Approach:

Using Morris Preorder Traversal, we can traverse the tree


without using a stack or recursion. The idea of Morris Traversal
is inspired by the Threaded Binary Tree. In this traversal, we first
establish links to the inorder predecessor and print the data
using these links, and finally revert the changes to restore the
original tree structure. Although the tree is temporarily modified
during the traversal, it is reverted back to its original shape after
completion.

The algorithm for Preorder is almost similar to Morris traversal for


Inorder.

Initialize the current node as the root of the binary tree.


If the left child of the current node is NULL, print the current node’s
value and move to its right child.
If the left child exists, find the rightmost node in the left subtree
(inorder predecessor) of the current node.
Establish Links:
If the right child of the inorder predecessor points to the
current node, it indicates that the left subtree has been

https://www.geeksforgeeks.org/morris-traversal-for-preorder/?ref=lbp 2/4
3/30/25, 4:11 PM Morris traversal for Preorder | GeeksforGeeks

visited. Set the right child of the predecessor to NULL and


move to the right child of the current node.
If it doesn’t point to the current node, print the current
node’s value, set the predecessor’s right child to the
current node (to create a temporary link), and move to the
left child.
Continue this process until the current node becomes NULL,
effectively visiting all nodes in preorder without using additional
space for a stack or recursion.

Following is the implementation of the above algorithm.

C++ C Java Python C# JavaScript

// JavaScript program for Morris Preorder traversal

class Node {
constructor(x) {
this.data = x;
this.left = this.right = null;
}
}

function preOrder(root) {
while (root) {

// If left child is null, print


// the current node data. Move to right child.
if (root.left === null) {
console.log(root.data + " ");
root = root.right;
}
else {

// Find inorder predecessor


let current = root.left;
while (current.right && current.right !== root)
current = current.right;

// If the right child of inorder predecessor


// already points to this node
if (current.right === root) {
current.right = null;
root = root.right;
}

// If right child doesn't point to this node,


// then print this node and make right child
// point to this node
else {
console.log(root.data + " ");
https://www.geeksforgeeks.org/morris-traversal-for-preorder/?ref=lbp 3/4
3/30/25, 4:11 PM Morris traversal for Preorder | GeeksforGeeks
current.right = root;
root = root.left;
}
}
}
}

const root = new Node(1);


root.left = new Node(2);
root.right = new Node(3);
root.left.left = new Node(4);
root.left.right = new Node(5);
root.right.left = new Node(6);
root.right.right = new Node(7);

preOrder(root);
console.log();

Output

1 2 4 5 3 6 7

Time Complexity: O(n), we visit every node at most once.


Auxiliary Space: O(1)

Limitations:

Morris’s traversal modifies the tree during the process. It establishes


the right links while moving down the tree and resets the right links
while moving up the tree. So the algorithm cannot be applied if right
operations are not allowed.

https://www.geeksforgeeks.org/morris-traversal-for-preorder/?ref=lbp 4/4
3/30/25, 4:12 PM Iterative Preorder Traversal | GeeksforGeeks

Iterative Preorder Traversal


Last Updated : 22 May, 2024

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 process to print


Preorder traversal.

1. Create an empty stack nodeStack and push root node to


stack.
2. Do the following while nodeStack is not empty.
1. Pop an item from the stack and print it.
2. Push right child of a popped item to stack
3. Push left child of a popped item to stack

The right child is pushed before the left child to make sure that
the left subtree is processed first.

C++ Java Python C# JavaScript

// Javascript program to implement iterative


// preorder traversal

// A binary tree node


class Node
{
constructor(item)
{
this.data = item;

https://www.geeksforgeeks.org/iterative-preorder-traversal/?ref=lbp 1/7
3/30/25, 4:12 PM Iterative Preorder Traversal | GeeksforGeeks
this.left = null;
this.right = null;
}
}

var root = null;

// An iterative process to print preorder


// traversal of Binary tree
function iterativePreorder(node)
{

// Base Case
if (node == null)
{
return;
}

// Create an empty stack and push root to it


var nodeStack = [];
nodeStack.push(root);

/* Pop all items one by one. Do following


for every popped item
a) print it
b) push its right child
c) push its left child
Note that right child is pushed first so
that left is processed first */
while (nodeStack.length > 0)
{

// Pop the top item from stack and print it


var mynode = nodeStack[nodeStack.length - 1];
document.write(mynode.data + " ");
nodeStack.pop();

// Push right and left children of


// the popped node to stack
if (mynode.right != null)
{
nodeStack.push(mynode.right);
}
if (mynode.left != null)
{
nodeStack.push(mynode.left);
}
}
}

// Driver Code
root = new Node(10);
root.left = new Node(8);
root.right = new Node(2);
root.left.left = new Node(3);
root.left.right = new Node(5);
root.right.left = new Node(2);

iterativePreorder(root);

https://www.geeksforgeeks.org/iterative-preorder-traversal/?ref=lbp 2/7
3/30/25, 4:12 PM Iterative Preorder Traversal | GeeksforGeeks

// This code is contributed by itsok

Output

10 8 3 5 2 2

Time Complexity: O(N)


Auxiliary Space: O(H), where H is the height of the tree.

Another Solution: In the previous solution we can see that the left
child is popped as soon as it is pushed to the stack, therefore it is not
required to push it into the stack.

The idea is to start traversing the tree from the root node, and keep
printing the left child while exists and simultaneously, push the right
child of every node in an auxiliary stack. Once we reach a null node,
pop a right child from the auxiliary stack and repeat the process while
the auxiliary stack is not-empty.

This is a micro-optimization over the previous approach, both the


solutions use asymptotically similar auxiliary space.

Below is the implementation of the above approach:

C++ Java Python C# JavaScript

class Node
{
constructor(item)
{
this.left = null;
this.right = null;
this.data = item;
}
}

let root;

// Iterative function to do Preorder


// traversal of the tree
function preorderiterative(node)
{
if (node == null)
{
return;
}

https://www.geeksforgeeks.org/iterative-preorder-traversal/?ref=lbp 3/7
3/30/25, 4:12 PM Iterative Preorder Traversal | GeeksforGeeks
let st = [];

// Start from root node (set curr


// node to root node)
let curr = node;

// Run till stack is not empty or


// current is not NULL
while (curr != null || st.length > 0)
{

// Print left children while exist


// and keep pushing right into the
// stack.
while (curr != null)
{
document.write(curr.data + " ");

if (curr.right != null)
st.push(curr.right);

curr = curr.left;
}

// We reach when curr is NULL, so We


// take out a right child from stack
if (st.length > 0)
{
curr = st.pop();
}
}
}

function preorderIterative()
{
preorderiterative(root);
}

// Driver code
root = new Node(10);
root.left = new Node(20);
root.right = new Node(30);
root.left.left = new Node(40);
root.left.left.left = new Node(70);
root.left.right = new Node(50);
root.right.left = new Node(60);
root.left.left.right = new Node(80);

preorderIterative();

// This code is contributed by decode2207

Output

10 20 40 70 80 50 30 60

https://www.geeksforgeeks.org/iterative-preorder-traversal/?ref=lbp 4/7
3/30/25, 4:12 PM Iterative Preorder Traversal | GeeksforGeeks

Time Complexity: O(N)


Auxiliary Space: O(H), where H is the height of the tree.

ANOTHER APPROACH:
Intuition:

Using Morris Traversal, we can traverse the tree without using


stack and recursion. The algorithm for Preorder is almost similar
to Morris traversal for Inorder.

1…If left child is null, print the current node data. Move to right
child.
….Else, Make the right child of the inorder predecessor point to
the current node. Two cases arise:
………a) The right child of the inorder predecessor already points
to the current node. Set right child to NULL. Move to right child
of current node.
………b) The right child is NULL. Set it to the current node. Print
the current node’s data and move to left child of current node.
2…Iterate until the current node is not NULL.

Implementation:

C++ Java Python C# JavaScript

class Node {
constructor(item) {
this.data = item;
this.left = this.right = null;
}
}

class BinaryTree {
constructor() {
this.root = null;
}

morrisTraversalPreorder() {
this.morrisTraversalPreorderHelper(this.root);
}

// Preorder traversal without recursion and without stack


morrisTraversalPreorderHelper(node) {
https://www.geeksforgeeks.org/iterative-preorder-traversal/?ref=lbp 5/7
3/30/25, 4:12 PM Iterative Preorder Traversal | GeeksforGeeks
while (node) {
// If left child is null, print the current node data. Move
to right child.
if (node.left === null) {
process.stdout.write(node.data + " ");
node = node.right;
} else {
// Find inorder predecessor
let current = node.left;
while (current.right !== null && current.right !== node)
{
current = current.right;
}

// If the right child of inorder predecessor already


points to this node
if (current.right === node) {
current.right = null;
node = node.right;
} else {
// If right child doesn't point to this node, then
print this node
// and make right child point to this node
process.stdout.write(node.data + " ");
current.right = node;
node = node.left;
}
}
}
}

preorder() {
this.preorderHelper(this.root);
}

// Function for Standard preorder traversal


preorderHelper(node) {
if (node !== null) {
process.stdout.write(node.data + " ");
this.preorderHelper(node.left);
this.preorderHelper(node.right);
}
}
}

// Driver program to test above functions


const tree = new BinaryTree();
tree.root = new Node(1);
tree.root.left = new Node(2);
tree.root.right = new Node(3);
tree.root.left.left = new Node(4);
tree.root.left.right = new Node(5);
tree.root.right.left = new Node(6);
tree.root.right.right = new Node(7);
tree.root.left.left.left = new Node(8);
tree.root.left.left.right = new Node(9);
tree.root.left.right.left = new Node(10);
tree.root.left.right.right = new Node(11);
tree.morrisTraversalPreorder();

https://www.geeksforgeeks.org/iterative-preorder-traversal/?ref=lbp 6/7
3/30/25, 4:12 PM Iterative Preorder Traversal | GeeksforGeeks
console.log("");
tree.preorder();

Output

1 2 4 8 9 5 10 11 3 6 7
1 2 4 8 9 5 10 11 3 6 7

Time Complexity: O(n), we visit every node at most once.


Auxiliary Space: O(1), we use a constant amount of space for
variables and pointers.

https://www.geeksforgeeks.org/iterative-preorder-traversal/?ref=lbp 7/7
3/30/25, 4:12 PM Iterative Postorder Traversal | Set 1 (Using Two Stacks) | GeeksforGeeks

Iterative Postorder Traversal | Set 1 (Using Two


Stacks)
Last Updated : 04 Oct, 2024

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 1
Explanation: Postorder traversal (Left->Right->Root) of the tree
is 4 5 2 3 1.

Input:

https://www.geeksforgeeks.org/iterative-postorder-traversal/?ref=lbp 1/6
3/30/25, 4:12 PM Iterative Postorder Traversal | Set 1 (Using Two Stacks) | GeeksforGeeks

Output: 10 7 1 6 10 6 5 8
Explanation: Postorder traversal (Left->Right->Root) of the tree
is 10 7 1 6 10 6 5 8 .

Approach:

The idea is to push reverse Postorder traversal to a stack. Once


we have the reversed postorder traversal in a stack, we can just
pop all items one by one from the stack and print them; this
order of printing will be in postorder because of the LIFO
property of stacks. Now the question is, how to get reversed
postorder elements in a stack – the second stack is used for this
purpose. For example, in the following tree, we need to get 1, 3,
7, 6, 2, 5, 4 in a stack. If we take a closer look at this sequence,
we can observe that this sequence is very similar to the preorder
traversal. The only difference is that the right child is visited
before left child, and therefore the sequence is “root right left”
instead of “root left right”. So, we can do something like iterative
preorder traversal with the following differences:
a) Instead of printing an item, we push it to a stack.
b) We push the left subtree before the right subtree.

Follow the steps below to solve the problem:

Push root to first stack.


Loop until first stack is not empty
Pop a node from first stack and push it to second stack

https://www.geeksforgeeks.org/iterative-postorder-traversal/?ref=lbp 2/6
3/30/25, 4:12 PM Iterative Postorder Traversal | Set 1 (Using Two Stacks) | GeeksforGeeks

Push left and right children of the popped node to first


stack
Print contents of second stack

Consider the following tree:

Following are the steps to print Postorder traversal of the above tree
using two stacks:

1. Push 1 to first stack


First stack: 1
Second stack: empty

2. Pop 1 from first stack and push it to second stack. Push left
and right children of 1 to first stack
First stack: 2, 3
Second stack: 1

3. Pop 3 from first stack and push it to second stack. Push left
and right children of 3 to first stack
First stack: 2, 6, 7
Second stack: 1, 3

4. Pop 7 from first stack and push it to second stack.


First stack: 2, 6
Second stack: 1, 3, 7

https://www.geeksforgeeks.org/iterative-postorder-traversal/?ref=lbp 3/6
3/30/25, 4:12 PM Iterative Postorder Traversal | Set 1 (Using Two Stacks) | GeeksforGeeks

5. Pop 6 from first stack and push it to second stack.


First stack: 2
Second stack: 1, 3, 7, 6

6. Pop 2 from first stack and push it to second stack. Push left
and right children of 2 to first stack
First stack: 4, 5
Second stack: 1, 3, 7, 6, 2

7. Pop 5 from first stack and push it to second stack.


First stack: 4
Second stack: 1, 3, 7, 6, 2, 5

8. Pop 4 from first stack and push it to second stack.


First stack: Empty
Second stack: 1, 3, 7, 6, 2, 5, 4

The algorithm stops here since there are no more items in the
first stack. Observe that the contents of second stack are in
postorder manner. Print them.

Below is the implementation of the above approach:

C++ C Java Python C# JavaScript

// JavaScript program to find the postorder


// traversal using 2 Stacks
class Node {
constructor(key) {
this.key = key;
this.left = null;
this.right = null;
}
}

// Function to perform postorder traversal


// using two stacks
function postOrder(root) {
const ans = [];
if (!root) return ans;

const stk1 = [root];


const stk2 = [];

// Loop while stk1 is not empty


while (stk1.length > 0) {

https://www.geeksforgeeks.org/iterative-postorder-traversal/?ref=lbp 4/6
3/30/25, 4:12 PM Iterative Postorder Traversal | Set 1 (Using Two Stacks) | GeeksforGeeks
const node = stk1.pop();

// Push node's key to stk2


stk2.push(node.key);

// Push left and right children to stk1


if (node.left) stk1.push(node.left);
if (node.right) stk1.push(node.right);
}

// Collect nodes from s2 in postorder


while (stk2.length > 0) {
ans.push(stk2.pop());
}

return ans;
}

// Representation of input binary tree:


// 1
// / \
// 2 3
// / \
// 4 5

const root = new Node(1);


root.left = new Node(2);
root.right = new Node(3);
root.left.left = new Node(4);
root.left.right = new Node(5);

const result = postOrder(root);


console.log(result.join(' '));

Output

4 5 2 3 1

Time complexity: O(n), since the algorithm processes each node


exactly twice (once when pushed to s1 and once when popped from
s2), where n is the number of nodes.
Auxiliary space: O(n), due to the two stacks, each holding up to n
nodes at different points in the traversal.

Realted articles:

Postorder Traversal of Binary Tree


Iterative Postorder Traversal | Set 2 (Using One Stack)
Iterative Postorder traversal | Set 3

https://www.geeksforgeeks.org/iterative-postorder-traversal/?ref=lbp 5/6
3/30/25, 4:12 PM Iterative Postorder Traversal | Set 1 (Using Two Stacks) | GeeksforGeeks

https://www.geeksforgeeks.org/iterative-postorder-traversal/?ref=lbp 6/6
3/30/25, 4:12 PM Diagonal Traversal of Binary Tree | GeeksforGeeks

Diagonal Traversal of Binary Tree


Last Updated : 26 Sep, 2024

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 4
Explanation: The above is the diagonal elements in a binary tree
that belong to the same line.

Using Recursion and Hashmap – O(n) Time and O(n) Space:

To find the diagonal view of a binary tree, we perform a


recursive traversal that stores nodes in a hashmap based on

https://www.geeksforgeeks.org/diagonal-traversal-of-binary-tree/?ref=lbp 1/3
3/30/25, 4:12 PM Diagonal Traversal of Binary Tree | GeeksforGeeks

their diagonal levels. Left children increase the diagonal level,


while right children remain on the same level.

Below is the implementation of the above approach:

C++ Java Python C# JavaScript

// JavaScript program to print diagonal view

class Node {
constructor(x) {
this.key = x;
this.left = null;
this.right = null;
}
}

// Recursive function to print diagonal view


function diagonalRecur(root, level, levelData) {

// Base case
if (root === null)
return;

// Append the current node into hash map.


if (!levelData[level]) {
levelData[level] = [];
}
levelData[level].push(root.key);

// Recursively traverse the left subtree.


diagonalRecur(root.left, level + 1, levelData);

// Recursively traverse the right subtree.


diagonalRecur(root.right, level, levelData);
}

// function to print diagonal view


function diagonal(root) {
let ans = [];

// Create a hash map to store each


// node at its respective level.
let levelData = {};
diagonalRecur(root, 0, levelData);

let level = 0;

// Insert into answer level by level.


while (level in levelData) {
ans = ans.concat(levelData[level]);
level++;
}

return ans;
https://www.geeksforgeeks.org/diagonal-traversal-of-binary-tree/?ref=lbp 2/3
3/30/25, 4:12 PM Diagonal Traversal of Binary Tree | GeeksforGeeks
}

function printList(v) { console.log(v.join(" ")); }

// Create a hard coded tree


// 8
// / \
// 3 10
// / / \
// 1 6 14
// / \ /
// 4 7 13
let root = new Node(8);
root.left = new Node(3);
root.right = new Node(10);
root.left.left = new Node(1);
root.right.left = new Node(6);
root.right.right = new Node(14);
root.right.right.left = new Node(13);
root.right.left.left = new Node(4);
root.right.left.right = new Node(7);

let ans = diagonal(root);


printList(ans);

Output

8 10 14 3 6 7 13 1 4

Time Complexity: O(n), where n is the number of nodes in the binary


tree.
Auxiliary Space: O(n), used in hash map.

Note: This approach may get time limit exceeded(TLE) error as it is


not an optimized approach. For optimized approach, Please refer to
Iterative diagonal traversal of binary tree

https://www.geeksforgeeks.org/diagonal-traversal-of-binary-tree/?ref=lbp 3/3
3/30/25, 4:12 PM Boundary Traversal of binary tree | GeeksforGeeks

Boundary Traversal of binary tree


Last Updated : 08 Feb, 2025

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:

1. left boundary (nodes on left excluding leaf nodes)


2. leaves (consist of only the leaf nodes)
3. right boundary (nodes on right excluding leaf nodes)

The left boundary is defined as the path from the root to the left-
most leaf node (excluding leaf node itself).
The right boundary is defined as the path from the root to the right-
most leaf node (excluding leaf node itself).

Note: If the root doesn’t have a left subtree or right subtree, then the
root itself is the left or right boundary.

Table of Content

https://www.geeksforgeeks.org/boundary-traversal-of-binary-tree/?ref=lbp 1/6
3/30/25, 4:12 PM Boundary Traversal of binary tree | GeeksforGeeks

[Approach – 1] Using Recursion – O(n) Time and O(h) Space


[Approach – 2] Using Iteration and Morris Traversal – O(n) Time and
O(1) Space

[Approach – 1] Using Recursion – O(n) Time and O(h) Space

The idea is to traverse the boundary of the binary tree in three


parts:

Collect Left Boundary Nodes: Collects all nodes from the


root’s left child, excluding leaf nodes, until a leaf is reached.
Collect Leaf Nodes: Using recursion traverse the tree and
collect all leaf nodes in the result.
Collect Right Boundary Nodes: Collects all nodes from the
root’s right child, excluding leaf nodes, in reverse order.

By combining these parts, we achieve the desired boundary


traversal. Each part is collected using recursive functions for left
boundary, leaf nodes, and right boundary traversal.

C++ Java Python C# JavaScript

▸ {...}

function isLeaf(node) {
return !node.left && !node.right;
}

// Function to collect left boundary nodes


// (top-down order)
function collectBoundaryLeft(root, res) {
if (!root || isLeaf(root)) return;

res.push(root.data);
if (root.left) {
collectBoundaryLeft(root.left, res);
} else if (root.right) {
collectBoundaryLeft(root.right, res);
}
}

// Function to collect all leaf nodes


function collectLeaves(root, res) {
if (!root) return;

https://www.geeksforgeeks.org/boundary-traversal-of-binary-tree/?ref=lbp 2/6
3/30/25, 4:12 PM Boundary Traversal of binary tree | GeeksforGeeks

if (isLeaf(root)) {
res.push(root.data);
return;
}

collectLeaves(root.left, res);
collectLeaves(root.right, res);
}

// Function to collect right boundary nodes


// (bottom-up order)
function collectBoundaryRight(root, res) {
if (!root || isLeaf(root)) return;

if (root.right) {
collectBoundaryRight(root.right, res);
} else if (root.left) {
collectBoundaryRight(root.left, res);
}

res.push(root.data);
}

// Function to find Boundary Traversal of Binary Tree


function boundaryTraversal(root) {
const res = [];

if (!root) return res;

// Add root data if it's not a leaf


if (!isLeaf(root)) {
res.push(root.data);
}

// Collect left boundary


collectBoundaryLeft(root.left, res);

// Collect leaf nodes


collectLeaves(root, res);

// Collect right boundary


collectBoundaryRight(root.right, res);

return res;
}

▸ {...}

Output

20 8 4 10 14 25 22

https://www.geeksforgeeks.org/boundary-traversal-of-binary-tree/?ref=lbp 3/6
3/30/25, 4:12 PM Boundary Traversal of binary tree | GeeksforGeeks

[Approach – 2] Using Iteration and Morris Traversal – O(n) Time


and O(1) Space

The idea is to reduce the auxiliary space used by the memory


stack in the above approach. This approach is similar to the
previous one, but instead of recursion, we use iteration to find
the left and right boundaries, and use Morris Traversal to find
the leaf nodes.

C++ Java Python C# JavaScript

▸ {...}
}

// Helper function to check if a node is a leaf


function isLeaf(node) {
return !node.left && !node.right;
}

// Function to collect the left boundary nodes


function collectBoundaryLeft(root, res) {
if (root === null) return;

let curr = root;


while (!isLeaf(curr)) {
res.push(curr.data);

if (curr.left) curr = curr.left;


else curr = curr.right;
}
}

// Function to collect the leaf nodes using Morris Traversal


function collectLeaves(root, res) {
let current = root;

while (current) {
if (!current.left) {
// If it's a leaf node
if (!current.right)
res.push(current.data);

current = current.right;
}
else {
// Find the inorder predecessor
let predecessor = current.left;
while (predecessor.right && predecessor.right !== current) {
predecessor = predecessor.right;
}

https://www.geeksforgeeks.org/boundary-traversal-of-binary-tree/?ref=lbp 4/6
3/30/25, 4:12 PM Boundary Traversal of binary tree | GeeksforGeeks
if (!predecessor.right) {
predecessor.right = current;
current = current.left;
}
else {
// If it's predecessor is a leaf node
if (!predecessor.left)
res.push(predecessor.data);

predecessor.right = null;
current = current.right;
}
}
}
}

// Function to collect the right boundary nodes


function collectBoundaryRight(root, res) {
if (root === null) return;

let curr = root;


const temp = [];
while (!isLeaf(curr)) {
temp.push(curr.data);

if (curr.right) curr = curr.right;


else curr = curr.left;
}

res.push(...temp.reverse());
}

// Function to perform boundary traversal


function boundaryTraversal(root) {
const res = [];

if (!root) return res;

// Add root data if it's not a leaf


if (!isLeaf(root)) res.push(root.data);

// Collect left boundary


collectBoundaryLeft(root.left, res);

// Collect leaf nodes


collectLeaves(root, res);

// Collect right boundary


collectBoundaryRight(root.right, res);

return res;
}

▸ {...}

Output

https://www.geeksforgeeks.org/boundary-traversal-of-binary-tree/?ref=lbp 5/6
3/30/25, 4:12 PM Boundary Traversal of binary tree | GeeksforGeeks

20 8 4 10 14 25 22

https://www.geeksforgeeks.org/boundary-traversal-of-binary-tree/?ref=lbp 6/6
3/30/25, 4:20 PM Calculate depth of a full Binary tree from Preorder | GeeksforGeeks

Calculate depth of a full Binary tree from Preorder


Last Updated : 14 Oct, 2024

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 node

The given tree can be seen as a full binary tree where every node has
0 or two children. The two children of a node can be ‘n’ or a or a mix
of both.

Examples :

Input: s = “nlnll”
Output: 2
Explanation: Below is the representation of the tree formed from
the string with depth equals to 2.

Input: s = “nlnnlll”
https://www.geeksforgeeks.org/calculate-depth-full-binary-tree-preorder/?ref=lbp 1/3
3/30/25, 4:20 PM Calculate depth of a full Binary tree from Preorder | GeeksforGeeks

Output: 3
Explanation: Below is the representation of the tree formed from
the string with depth equals to 3.

Approach:

The idea is to traverse the binary tree using preorder traversal


recursively using the given preorder sequence. If the index at
current node is out of bounds or the node is equal to ‘l’, then
return 0. Otherwise, recursively traverse the left subtree and
right subtree, and return 1 + max(left, right) as output.

Below is the implementation of the above approach:

C++ Java Python C# JavaScript

// Javascript program to find height of


// full binary tree using preorder

// function to return max of left subtree height


// or right subtree height
function findDepthRec(tree, n, index) {
if (index[0] >= n || tree[index[0]] === 'l')
return 0;

// calc height of left subtree (In preorder


// left subtree is processed before right)
index[0]++;
let left = findDepthRec(tree, n, index);

// calc height of right subtree


index[0]++;

https://www.geeksforgeeks.org/calculate-depth-full-binary-tree-preorder/?ref=lbp 2/3
3/30/25, 4:20 PM Calculate depth of a full Binary tree from Preorder | GeeksforGeeks
let right = findDepthRec(tree, n, index);

return Math.max(left, right) + 1;


}

function findDepth(tree) {

// index is represented as array to


// pass it by reference
let index = [0];
return findDepthRec(tree, tree.length, index);
}

const tree = "nlnnlll";


console.log(findDepth(tree));

Output

Time Complexity: O(n) , where n is the size of array.


Auxiliary Space: O(h)

https://www.geeksforgeeks.org/calculate-depth-full-binary-tree-preorder/?ref=lbp 3/3
3/30/25, 4:23 PM Construct a tree from Inorder and Level order traversals | Set 1 | GeeksforGeeks

Construct a tree from Inorder and Level order


traversals | Set 1
Last Updated : 30 Sep, 2024

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 order array. Find the index of this element in the in-
order array. Recursively create the left subtree from the
elements present on the left side to the current element in the
in-order array. Similarly, create the right subtree from the
elements present on the right side to the current element in the
in-order array.

https://www.geeksforgeeks.org/construct-tree-inorder-level-order-traversals/?ref=lbp 1/4
3/30/25, 4:23 PM Construct a tree from Inorder and Level order traversals | Set 1 | GeeksforGeeks

Below is the implementation of the above approach:

C++ Java Python C# JavaScript

// JavaScript Program to construct tree using


// inorder and levelorder traversals

class Node {
constructor(key) {
this.key = key;
this.left = null;
this.right = null;
}
}

// Function to find the index of an element.


function searchValue(inorder, value, s, e) {
for (let i = s; i <= e; i++) {
if (inorder[i] === value) {
return i;
}
}
return -1;
}

// Recursive function to build the binary tree.


function buildTreeRecur(inorder, level, s, e) {

// For empty array, return null


if (s > e) {
return null;
}

// create the root Node


const root = new Node(level[0]);

// find the index of first element of level array


// in the in-order array.
const index = searchValue(inorder, level[0], s, e);

// Level order array for left and right subtree.


const lLevel = [];
const rLevel = [];

// add the left and right elements to lLevel and


// rLevel
let l = 0, r = 0;
for (let i = 1; i < e - s + 1; i++) {
const j = searchValue(inorder, level[i], s, e);

// If the value is present in


// left subtree.
if (j < index) {
lLevel[l++] = level[i];
}
https://www.geeksforgeeks.org/construct-tree-inorder-level-order-traversals/?ref=lbp 2/4
3/30/25, 4:23 PM Construct a tree from Inorder and Level order traversals | Set 1 | GeeksforGeeks

// else it will be present in


// right subtree.
else {
rLevel[r++] = level[i];
}
}

// Recursively create the left and right subtree.


root.left = buildTreeRecur(inorder, lLevel, s, index - 1);
root.right = buildTreeRecur(inorder, rLevel, index + 1, e);

return root;
}

function buildTree(inorder, level, n) {


return buildTreeRecur(inorder, level, 0, n - 1);
}

function printInorder(head) {
if (!head) {
return;
}
printInorder(head.left);
console.log(head.key);
printInorder(head.right);
}

const inorder = [4, 8, 10, 12, 14, 20, 22];


const level = [20, 8, 22, 4, 12, 10, 14];
const n = inorder.length;

const root = buildTree(inorder, level, n);


printInorder(root);

Output

4 8 10 12 14 20 22

Time Complexity: O(n^3)


Auxiliary Space: O(n), where n is the number of nodes.

Related articles:

Construct a tree from Inorder and Level order traversals | Set 2


Construct Tree from given Inorder and Preorder traversals

https://www.geeksforgeeks.org/construct-tree-inorder-level-order-traversals/?ref=lbp 3/4
3/30/25, 4:23 PM Construct a tree from Inorder and Level order traversals | Set 1 | GeeksforGeeks

https://www.geeksforgeeks.org/construct-tree-inorder-level-order-traversals/?ref=lbp 4/4
3/30/25, 4:24 PM Check if a given Binary Tree is Sum Tree | GeeksforGeeks

Check if a given Binary Tree is Sum Tree


Last Updated : 19 Sep, 2024

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 considered a Sum Tree.

Example:

Input:

Output: True
Explanation: The above tree follows the property of Sum Tree.

Input:

https://www.geeksforgeeks.org/check-if-a-given-binary-tree-is-sumtree/?ref=lbp 1/7
3/30/25, 4:24 PM Check if a given Binary Tree is Sum Tree | GeeksforGeeks

Output: False
Explanation: The above tree doesn’t follows the property of Sum
Tree as 6 + 2 != 10.

Table of Content
[Naive Approach] By Checking Every Node – O(n^2) Time and O(h)
Space
[Expected Approach] Calculating left and right subtree sum directly
– O(n) Time and O(h) Space
[Alternate Approach] Using post order traversal – O(n) Time and
O(h) Space

[Naive Approach] By Checking Every Node – O(n^2) Time and


O(h) Space:

The idea is to get the sum in the left subtree and right subtree
for each node and compare it with the node’s value. Also
recursively check if the left and right subtree are sum trees.

Below is the implementation of the above approach:

C++ C Java Python C# JavaScript

// JavaScript program to check if Binary tree


// is sum tree or not

https://www.geeksforgeeks.org/check-if-a-given-binary-tree-is-sumtree/?ref=lbp 2/7
3/30/25, 4:24 PM Check if a given Binary Tree is Sum Tree | GeeksforGeeks
class Node {
constructor(x) {
this.data = x;
this.left = this.right = null;
}
}

// A utility function to get the sum of values in tree


function sum(root) {
if (root == null)
return 0;

return sum(root.left) + root.data + sum(root.right);


}

// Returns true if sum property holds for the given


// node and both of its children
function isSumTree(root) {

// If root is null or it's a leaf node then return true


if (root == null || (root.left == null && root.right == null))
return true;

// Get sum of nodes in left and right subtrees


let ls = sum(root.left);
let rs = sum(root.right);

// If the root and both of its children satisfy the


// property, return true else false
return root.data == ls + rs &&
isSumTree(root.left) &&
isSumTree(root.right);
}

// create hard coded tree


// 26
// / \
// 10 3
// / \ \
// 4 6 3
let root = new Node(26);
root.left = new Node(10);
root.right = new Node(3);
root.left.left = new Node(4);
root.left.right = new Node(6);
root.right.right = new Node(3);

if (isSumTree(root)) {
console.log("True");
} else {
console.log("False");
}

Output

True

https://www.geeksforgeeks.org/check-if-a-given-binary-tree-is-sumtree/?ref=lbp 3/7
3/30/25, 4:24 PM Check if a given Binary Tree is Sum Tree | GeeksforGeeks

Time Complexity: O(n^2), where n are the number of nodes in binary


tree.
Auxiliary Space: O(h)

[Expected Approach] Calculating left and right subtree sum


directly – O(n) Time and O(h) Space:

The idea is to first check if left and right subtrees are sum trees.
If they are, then the sum of left and right subtrees can easily be
obtained in O(1) time.

Step by Step implementation:

1. For a given root node, recursively check if left subtree and right
subtree are sum trees. If one of them or both are not sum tree,
simply return false.
2. If both of them are sum trees, then we can find the sum of left
subtree and right subtree in O(1) using the following conditions:
If the root is null, then the sum is 0.
If the root is a leaf node, then sum is equal to root’s value.
Otherwise, the sum if equal to twice of root’s value. This is
because this subtree is a sum tree. So the sum of this subtree’s
subtree is equal to root’s value. So the total sum becomes
2*root->val.

Below is the implementation of the above approach:

C++ C Java Python C# JavaScript

class Node {
constructor(x) {
this.data = x;
this.left = null;
this.right = null;
}
}

// Utility function to check if the given


// node is leaf or not
function isLeaf(node) {
if (node === null) return false;

https://www.geeksforgeeks.org/check-if-a-given-binary-tree-is-sumtree/?ref=lbp 4/7
3/30/25, 4:24 PM Check if a given Binary Tree is Sum Tree | GeeksforGeeks
if (node.left === null && node.right === null) return true;
return false;
}

function isSumTree(root) {
let ls, rs;

// If node is null or it's a leaf node then return true


if (root === null || isLeaf(root)) return true;

// If the left subtree and right subtree are sum trees,


// then we can find subtree sum in O(1).
if (isSumTree(root.left) && isSumTree(root.right)) {

// Get the sum of nodes in left subtree


if (root.left === null) ls = 0;
else if (isLeaf(root.left)) ls = root.left.data;
else ls = 2 * root.left.data;

// Get the sum of nodes in right subtree


if (root.right === null) rs = 0;
else if (isLeaf(root.right)) rs = root.right.data;
else rs = 2 * root.right.data;

// If root's data is equal to sum of nodes in left


// and right subtrees then return true else return false
return root.data === ls + rs;
}

// if either of left or right subtree is not


// sum tree, then return false.
return false;
}

// create hard coded tree


// 26
// / \
// 10 3
// / \ \
// 4 6 3
let root = new Node(26);
root.left = new Node(10);
root.right = new Node(3);
root.left.left = new Node(4);
root.left.right = new Node(6);
root.right.right = new Node(3);

if (isSumTree(root)) console.log("True");
else console.log("False");

Output

True

https://www.geeksforgeeks.org/check-if-a-given-binary-tree-is-sumtree/?ref=lbp 5/7
3/30/25, 4:24 PM Check if a given Binary Tree is Sum Tree | GeeksforGeeks

Time Complexity: O(n), where n are the number of nodes in binary


tree.
Auxiliary Space: O(h)

[Alternate Approach] Using post order traversal – O(n) Time


and O(h) Space:

The idea is recursively check if the left and right subtrees are
sum trees. If a subtree is sum tree, it will return the sum of its
root node, left tree and right tree. Otherwise it will return -1.

Step by step implementation:

1. For each current node, recursively check the left and right subtree
for sum tree.
2. If the subtree is sum tree, it will return the sum of its root node, left
tree and right tree.
3. Compare the sum of left subtree and right subtree with the root
node. If they are equal, return sum of root node, left subtree and
right subtree. Otherwise return -1.

Below is the implementation of the above approach:

C++ C Java Python C# JavaScript

// JavaScript program to check if


// Binary tree is sum tree or not

class Node {
constructor(x) {
this.data = x;
this.left = null;
this.right = null;
}
}

// returns sum if tree is SumTree


// else return -1
function isSumTree(root) {
if (root === null) return 0;

// If node is leaf node, return its value.


if (root.left === null && root.right === null) return root.data;

https://www.geeksforgeeks.org/check-if-a-given-binary-tree-is-sumtree/?ref=lbp 6/7
3/30/25, 4:24 PM Check if a given Binary Tree is Sum Tree | GeeksforGeeks
// Calculate left subtree sum
const ls = isSumTree(root.left);

// if left subtree is not sum tree, return -1.


if (ls === -1) return -1;

// Calculate right subtree sum


const rs = isSumTree(root.right);

// if right subtree is not sum tree, return -1.


if (rs === -1) return -1;

if (ls + rs === root.data) return ls + rs + root.data;


else return -1;
}

// create hard coded tree


// 26
// / \
// 10 3
// / \ \
// 4 6 3
let root = new Node(26);
root.left = new Node(10);
root.right = new Node(3);
root.left.left = new Node(4);
root.left.right = new Node(6);
root.right.right = new Node(3);

if (isSumTree(root) !== -1) console.log("True");


else console.log("False");

Output

True

Time Complexity: O(n), where n are the number of nodes in binary


tree.
Auxiliary Space: O(h)

https://www.geeksforgeeks.org/check-if-a-given-binary-tree-is-sumtree/?ref=lbp 7/7
3/30/25, 4:24 PM Check if two nodes are cousins in a Binary Tree | GeeksforGeeks

Check if two nodes are cousins in a Binary Tree


Last Updated : 23 Sep, 2024

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: True
Explanation: Node with the values 5 and 4 are on the same level
with different parents.

Input: a = 4, b = 5

https://www.geeksforgeeks.org/check-two-nodes-cousins-binary-tree/?ref=lbp 1/5
3/30/25, 4:24 PM Check if two nodes are cousins in a Binary Tree | GeeksforGeeks

Output: False
Explanation: Node with the values 5 and 4 are on the same level
with same parent.

Table of Content
Using Depth First Search
Using Breadth-First Search

Using Depth First Search:

The idea is to check the level of both the given node values
using depth first search. If their levels are same, then check if
they are children of same or different nodes. If they have same
parent, then return false. else, return true.

Below is the implementation of the above approach.

C++ C Java Python C# JavaScript

// JavaScript program to
// check if two Nodes are Cousins
class Node {
constructor(x) {
this.data = x;
this.left = this.right = null;
}
}

// Recursive function to check if two Nodes are siblings


function isSibling(root, a, b) {
https://www.geeksforgeeks.org/check-two-nodes-cousins-binary-tree/?ref=lbp 2/5
3/30/25, 4:24 PM Check if two nodes are cousins in a Binary Tree | GeeksforGeeks

// Base case
if (root == null)
return false;

if (root.left != null && root.right != null &&


root.left.data === a && root.right.data === b)
return true;

if (root.left != null && root.right != null &&


root.left.data === b && root.right.data === a)
return true;

return isSibling(root.left, a, b) ||
isSibling(root.right, a, b);
}

// Recursive function to find level of Node with


// data = value in a binary tree
function level(root, value, lev) {

// base cases
if (root == null)
return 0;
if (root.data === value)
return lev;

// Return level if Node is present in left subtree


let l = level(root.left, value, lev + 1);
if (l !== 0)
return l;

// Else search in right subtree


return level(root.right, value, lev + 1);
}

// Returns true if a and b are cousins, otherwise false


function isCousins(root, a, b) {

// 1. The two Nodes should be on the same level


// in the binary tree.
// 2. The two Nodes should not be siblings
// (means that they should not have the same parent Node).

if (a === b)
return false;

let aLevel = level(root, a, 1);


let bLevel = level(root, b, 1);

// if a or b does not exist in the tree


if (aLevel === 0 || bLevel === 0)
return false;

return aLevel === bLevel && !isSibling(root, a, b);


}

// create hard coded tree


// 1

https://www.geeksforgeeks.org/check-two-nodes-cousins-binary-tree/?ref=lbp 3/5
3/30/25, 4:24 PM Check if two nodes are cousins in a Binary Tree | GeeksforGeeks
// / \
// 2 3
// / \
// 5 4
let root = new Node(1);
root.left = new Node(2);
root.right = new Node(3);
root.left.left = new Node(4);
root.right.right = new Node(5);

let a = 4, b = 5;

if (isCousins(root, a, b)) {
console.log("True");
} else {
console.log("False");
}

Output

True

Time Complexity O(n), where n are the number of nodes in binary


tree.
Auxiliary complexity: O(h), where h is the height of the tree.

In a depth-first search (DFS) approach to check if two nodes are


cousins, we traverse the tree three times, resulting in a time
complexity O(3n).

Using Breadth-First Search :

The idea is to use a queue to traverse the tree in a level-order


manner. This allows us to explore all nodes at a given depth
before moving deeper. If the two nodes are found at the same
level and are not siblings, then we return true, indicating they
are cousins. Otherwise, we return false, as this means they
either do not share the same depth or are sibling. Please Refer to
Check if two nodes are cousins in a Binary Tree using BFS for
implementation.

Time Complexity O(n), where n are the number of nodes in binary


tree.

https://www.geeksforgeeks.org/check-two-nodes-cousins-binary-tree/?ref=lbp 4/5
3/30/25, 4:24 PM Check if two nodes are cousins in a Binary Tree | GeeksforGeeks

Auxiliary Space: O(n), if the tree is completely unbalanced, the


maximum size of the queue can grow to O(n).

https://www.geeksforgeeks.org/check-two-nodes-cousins-binary-tree/?ref=lbp 5/5
3/30/25, 4:24 PM Check if removing an edge can divide a Binary Tree in two halves | GeeksforGeeks

Check if removing an edge can divide a Binary


Tree in two halves
Last Updated : 26 Oct, 2024

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 : True
Explanation: Removing edge 5-6 creates two trees of equal size.

Input:

https://www.geeksforgeeks.org/check-if-removing-an-edge-can-divide-a-binary-tree-in-two-halves/?ref=lbp 1/6
3/30/25, 4:24 PM Check if removing an edge can divide a Binary Tree in two halves | GeeksforGeeks

Output : False
Explanation: There is no edge whose removal creates two trees
of equal size.

Table of Content
[Naive Approach] Recursive Method – O(n^2) Time and O(h) Space
[Expected Approach] Using Bottom-Up Manner- O(n) Time and
O(h) Space

[Naive Approach] Recursive Method – O(n^2) Time and O(h)


Space

The idea is to count the number of nodes in the tree. Let count of
all nodes be n. Traverse the tree again and for each node, find
size of subtree rooted with this node. Let cnt be the size of
subtree size. If n-cnt is equal to cnt, then return true. Otherwise
recursively check for left and right subtree.

Below is the implementation of the above approach:

C++ C Java Python C# JavaScript

// JavaScript program to check if there exist an edge whose


// removal creates two trees of same size

class Node {
constructor(x) {
this.data = x;
https://www.geeksforgeeks.org/check-if-removing-an-edge-can-divide-a-binary-tree-in-two-halves/?ref=lbp 2/6
3/30/25, 4:24 PM Check if removing an edge can divide a Binary Tree in two halves | GeeksforGeeks
this.left = null;
this.right = null;
}
}

// To calculate size of tree with given root


function countNodes(root) {
if (root === null) return 0;
return countNodes(root.left) +
countNodes(root.right) + 1;
}

// This function returns true if there is an edge


// whose removal can divide the tree in two halves
function checkRec(root, n) {

// Base case
if (root === null) return false;

// find the size of current subtree


const cnt = countNodes(root);

// If unlinking the current subtree from


// main tree creates two trees of same size,
// return true.
if (cnt === n - cnt) return true;

// Check for rest of the nodes


return checkRec(root.left, n) ||
checkRec(root.right, n);
}

// This function mainly uses checkRec()


function check(root) {

// Count total nodes in given tree


const n = countNodes(root);

// Now recursively check all nodes


return checkRec(root, n);
}

// Binary tree
// 5
// / \
// 1 6
// / / \
// 3 7 4
const root = new Node(5);
root.left = new Node(1);
root.right = new Node(6);
root.left.left = new Node(3);
root.right.left = new Node(7);
root.right.right = new Node(4);

if (check(root)) {
console.log("True");
} else {

https://www.geeksforgeeks.org/check-if-removing-an-edge-can-divide-a-binary-tree-in-two-halves/?ref=lbp 3/6
3/30/25, 4:24 PM Check if removing an edge can divide a Binary Tree in two halves | GeeksforGeeks
console.log("False");
}

Output

True

[Expected Approach] Bottom-Up Manner – O(n) Time and O(h)


Space

The idea is to traverse tree in bottom up manner and while


traversing, for each node, find the size of the subtree and check
if the current node follows the required property.

Below is the implementation of above approach:

C++ Java Python C# JavaScript

// JavaScript program to check if there exist an edge whose


// removal creates two trees of same size

class Node {
constructor(x) {
this.data = x;
this.left = null;
this.right = null;
}
}

// To calculate size of tree with given root


function countNodes(root) {
if (root === null)
return 0;
return countNodes(root.left) +
countNodes(root.right) + 1;
}

// This function returns size of tree rooted with given


// root. It also sets "ans" as true if there is an edge
// whose removal divides tree in two halves.
// n is size of tree
function checkRec(root, n, ans) {

// Base case
if (root === null)
return 0;

// find the size of current subtree

https://www.geeksforgeeks.org/check-if-removing-an-edge-can-divide-a-binary-tree-in-two-halves/?ref=lbp 4/6
3/30/25, 4:24 PM Check if removing an edge can divide a Binary Tree in two halves | GeeksforGeeks
let cnt = checkRec(root.left, n, ans) +
checkRec(root.right, n, ans) + 1;

// If unlinking the current subtree from


// main tree creates two trees of same size,
// set ans to true
if (cnt === n - cnt)
ans.val = true;

// return the size of current subtree


return cnt;
}

// This function mainly uses checkRec()


function check(root) {

// Count total nodes in given tree


let n = countNodes(root);

let ans = {val: false};

// Now recursively check all nodes


checkRec(root, n, ans);

return ans.val;
}

// Binary tree
// 5
// / \
// 1 6
// / / \
// 3 7 4
let root = new Node(5);
root.left = new Node(1);
root.right = new Node(6);
root.left.left = new Node(3);
root.right.left = new Node(7);
root.right.right = new Node(4);

if (check(root)) {
console.log("True");
} else {
console.log("False");
}

Output

True

https://www.geeksforgeeks.org/check-if-removing-an-edge-can-divide-a-binary-tree-in-two-halves/?ref=lbp 5/6
3/30/25, 4:24 PM Check if removing an edge can divide a Binary Tree in two halves | GeeksforGeeks

https://www.geeksforgeeks.org/check-if-removing-an-edge-can-divide-a-binary-tree-in-two-halves/?ref=lbp 6/6

You might also like