0% found this document useful (0 votes)
9 views396 pages

Tree

The document provides an introduction to binary trees, detailing their structure, representation, and key terminologies such as nodes, root, and leaf nodes. It covers various operations including traversal, insertion, searching, and deletion, along with code examples in multiple programming languages. Additionally, it discusses properties and types of binary trees, highlighting their hierarchical nature and common algorithms used for manipulation.

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)
9 views396 pages

Tree

The document provides an introduction to binary trees, detailing their structure, representation, and key terminologies such as nodes, root, and leaf nodes. It covers various operations including traversal, insertion, searching, and deletion, along with code examples in multiple programming languages. Additionally, it discusses properties and types of binary trees, highlighting their hierarchical nature and common algorithms used for manipulation.

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/ 396

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
2

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
3

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
4
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
5
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
6
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
7
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
8
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
9
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
10
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
11
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
12
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
13
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
14
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
15

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
16
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
17

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

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
19

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
20
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
21

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
22
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
23
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
24
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
25
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
26
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
27
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
28
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
29
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
30
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
31

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
32
/ \ \
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
33
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
34

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
35

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
36
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
37

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
38
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
39
▸ {...}

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
40
// 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
41
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
42

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
43
// 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
44
// / \
// 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
45

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
46
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
47
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
48
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
49
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
50

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
51

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
52

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
53

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
54
}
}

// 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
55
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
56
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
57

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
58
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
59
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
60
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
61
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
62
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
63
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
64

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
65

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
66
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
67

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
68
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
69
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
70
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
71
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
72
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
73
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
74

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
75
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
76

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
77
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
78

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
79
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
80
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
81

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
82

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

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
84

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
85
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
86
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
87

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
88
[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
89
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
90
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
91
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
92
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
93

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
94
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
95
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
96
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
97
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
98
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
99
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
100
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
101
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
102

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
103

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
104
[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
105
}

// 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
106
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
107
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
108

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
109
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
110

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
111
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
112
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
113
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
114

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
115

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
116
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
117
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
118

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
119
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
120
// 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
121
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
122
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
123
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
124
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
125

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
126

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
127
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
128

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
129
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
130

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

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
132
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
133
}

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
134

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
135
[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
136
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
137
[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
138
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
139
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
140

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
141
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
142
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
143

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
144

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
145
// 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
146

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
147

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
148

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
149
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
150
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
151
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
152
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
153
// 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
154

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
155

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
156
// 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
157
// / \
// 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
158
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
159

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
160

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
161
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
162
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
163
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
164

https://www.geeksforgeeks.org/check-if-removing-an-edge-can-divide-a-binary-tree-in-two-halves/?ref=lbp 6/6
3/30/25, 4:24 PM Check whether a given binary tree is perfect or not | GeeksforGeeks
165

Check whether a given binary tree is perfect or


not
Last Updated : 26 Oct, 2024

Given a Binary Tree, the task is to check whether the given Binary Tree
is a perfect Binary Tree or not.
Note:

A Binary tree is a Perfect Binary Tree in which all internal nodes


have two children and all leaves are at the same level.
A Perfect Binary Tree of height h has 2h – 1 nodes.

Examples:

Input:

Output: True
Explanation: The above tree is the perfect binary tree as all
nodes have all nodes have two children and all leaves are at the
same level.

Input:

https://www.geeksforgeeks.org/check-weather-given-binary-tree-perfect-not/?ref=lbp 1/5
3/30/25, 4:24 PM Check whether a given binary tree is perfect or not | GeeksforGeeks
166

Output: False
Explanation: The above tree is not a perfect binary tree since not
all nodes have two children.

Table of Content
[Expected Approach – 1] Using Recursive Method – O(n) Time and
O(h) Space
[Expected Approach – 2] Using level order traversal – O(n) Time
and O(n) Space

[Expected Approach – 1] Using Recursive Method – O(n) Time


and O(h) Space

The idea is to find the depth of the tree (lets say d) and then
check that all the internal nodes have two child nodes and all
leaf nodes are at depth d. If not, then return false.

Below is the implementation of the above approach:

C++ C Java Python C# JavaScript

// JavaScript program to check if a


// given binary tree is perfect

class Node {
constructor(x) {
this.data = x;
this.left = null;
https://www.geeksforgeeks.org/check-weather-given-binary-tree-perfect-not/?ref=lbp 2/5
3/30/25, 4:24 PM Check whether a given binary tree is perfect or not | GeeksforGeeks
167
this.right = null;
}
}

// Function to find depth of tree.


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

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

// Recursive function which checks if


// tree is perfect or not.
function isPerfectRecur(root, d) {

// Empty tree is also perfect


if (root === null) return true;

// If node is leaf, check if it


// is at depth d.
if (root.left === null && root.right === null)
return d === 1;

// If internal node does not have


// left or right node, return false.
if (root.left === null || root.right === null)
return false;

// Check left and right subtree


return isPerfectRecur(root.left, d-1)
&& isPerfectRecur(root.right, d-1);
}

function isPerfect(root) {

// Find depth of tree


let d = depth(root);

return isPerfectRecur(root, d);


}

// Binary tree
// 10
// / \
// 20 30
// / \ / \
// 40 50 60 70
let root = new Node(10);
root.left = new Node(20);
root.right = new Node(30);
root.left.left = new Node(40);
root.left.right = new Node(50);
root.right.left = new Node(60);
root.right.right = new Node(70);

if (isPerfect(root)) {
console.log("True");

https://www.geeksforgeeks.org/check-weather-given-binary-tree-perfect-not/?ref=lbp 3/5
3/30/25, 4:24 PM Check whether a given binary tree is perfect or not | GeeksforGeeks
168
} else {
console.log("False");
}

Output

True

[Expected Approach – 2] Using level order traversal – O(n)


Time and O(n) Space

The idea is to perform a level-order traversal of the binary tree


using a queue. By traversing the tree level by level, we can check
if the tree satisfies the conditions of a perfect binary tree.

Below is the implementation of the above approach:

C++ Java Python C# JavaScript

// JavaScript program to check if a


// given binary tree is perfect

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

function isPerfect(root) {

if (root === null) return true;

let q = [];
q.push(root);

// to store the expected node


// count at a given level.
let nodeCnt = 1;

while (q.length > 0) {


let size = q.length;

// If number of expected nodes is


// not same, return false.
if (size !== nodeCnt) return false;

https://www.geeksforgeeks.org/check-weather-given-binary-tree-perfect-not/?ref=lbp 4/5
3/30/25, 4:24 PM Check whether a given binary tree is perfect or not | GeeksforGeeks
169
while (size-- > 0) {
let curr = q.shift();

if (curr.left !== null)


q.push(curr.left);
if (curr.right !== null)
q.push(curr.right);
}

// Next level will contain twice


// number of nodes.
nodeCnt *= 2;
}

return true;
}

// Binary tree
// 10
// / \
// 20 30
// / \ / \
// 40 50 60 70
let root = new Node(10);
root.left = new Node(20);
root.right = new Node(30);
root.left.left = new Node(40);
root.left.right = new Node(50);
root.right.left = new Node(60);
root.right.right = new Node(70);

if (isPerfect(root)) {
console.log("True");
} else {
console.log("False");
}

Output

True

https://www.geeksforgeeks.org/check-weather-given-binary-tree-perfect-not/?ref=lbp 5/5
3/30/25, 4:24 PM Check if a Binary Tree contains duplicate subtrees of size 2 or more | GeeksforGeeks
170

Check if a Binary Tree contains duplicate subtrees


of size 2 or more
Last Updated : 07 Nov, 2024

Given a Binary Tree, the task is to check whether the Binary tree
contains a duplicate sub-tree of size 2 or more.
Note: Two same leaf nodes are not considered as the subtree as the
size of a leaf node is one.

Example:

Input:

Output: True
Explanation:

https://www.geeksforgeeks.org/check-binary-tree-contains-duplicate-subtrees-size-2/?ref=lbp 1/6
3/30/25, 4:24 PM Check if a Binary Tree contains duplicate subtrees of size 2 or more | GeeksforGeeks
171

Table of Content
[Naive Approach] Generating All Subtrees – O(n^2) Time and O(n)
Space
[Expected Approach] Using Hash Set – O(n) Time and O(n) Space

[Naive Approach] Generating All Subtrees – O(n^2) Time and


O(n) Space

The idea is to generate all subtrees (of size greater than 1) of


the binary tree and store their Serialized Form in an array or
hash map. Then iterate through the array/map to check for
duplicate subtrees.

C++ Java Python C# JavaScript

// JavaScript program to find if there is a duplicate


// sub-tree of size 2 or more.

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

function dupSubRecur(root, map) {

// For null nodes,

https://www.geeksforgeeks.org/check-binary-tree-contains-duplicate-subtrees-size-2/?ref=lbp 2/6
3/30/25, 4:24 PM Check if a Binary Tree contains duplicate subtrees of size 2 or more | GeeksforGeeks
172
if (root === null) return "N";

// For leaf nodes, return its value in string.


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

// Process the left and right subtree.


let left = dupSubRecur(root.left, map);
let right = dupSubRecur(root.right, map);

// Generate the serialized form.


let curr = "";
curr += root.data;
curr += '*';
curr += left;
curr += '*';
curr += right;

// Store the subtree in map.


map[curr] = (map[curr] || 0) + 1;

return curr;
}

function dupSub(root) {
let map = {};

// Generate all the subtrees.


dupSubRecur(root, map);

// Check for all subtrees.


for (let val of Object.values(map)) {

// If subtree is duplicate.
if (val > 1) {
return 1;
}
}

return 0;
}

// A
// / \
// B C
// / \ \
// D E B
// / \
// D E
let root = new Node('A');
root.left = new Node('B');
root.right = new Node('C');
root.left.left = new Node('D');
root.left.right = new Node('E');
root.right.right = new Node('B');
root.right.right.left = new Node('D');
root.right.right.right = new Node('E');

https://www.geeksforgeeks.org/check-binary-tree-contains-duplicate-subtrees-size-2/?ref=lbp 3/6
3/30/25, 4:24 PM Check if a Binary Tree contains duplicate subtrees of size 2 or more | GeeksforGeeks
173
console.log(dupSub(root) === 1 ? "True" : "False");

Output

True

[Expected Approach] Using Hash Set – O(n) Time and O(n)


Space

The idea is to use a hash set to store the subtrees in Serialized


String Form. For a given subtree of size greater than 1, if its
equivalent serialized string already exists, then return true. If all
subtrees are unique, return false.

Step by step approach:

To identify duplicate subtrees efficiently, we only need to check


subtrees of size 2 or 3, as any larger duplicate subtree would
already contain smaller duplicate subtrees. This reduces the time
complexity of concatenating strings to O(1) by focusing only on
nodes where both children are either leaf nodes or one is a leaf and
the other is null.
Use a hash set, say s to track unique subtree structures and an
answer variable ans (initially set to false).
Define a function dupSubRecur that takes a node and returns a
string.
If the node is null, return “N”.
If it’s a leaf node, return its value as a string.
For internal nodes, first process the left and right subtrees.
If either subtree string is empty, return an empty string.
Otherwise, concatenate the current node with its left and
right subtree strings. If this concatenated string is in the
hash set, set ans to true; if not, insert it.
Return an empty string for each processed subtree, as upper
subtrees don’t need further processing.
https://www.geeksforgeeks.org/check-binary-tree-contains-duplicate-subtrees-size-2/?ref=lbp 4/6
3/30/25, 4:24 PM Check if a Binary Tree contains duplicate subtrees of size 2 or more | GeeksforGeeks
174
C++ Java Python C# JavaScript

// JavaScript program to find if there is a duplicate


// sub-tree of size 2 or more.

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

// Function which checks all the subtree of size 2 or


// 3 if they are duplicate.
function dupSubRecur(root, s, ans) {

// For null nodes,


if (root === null) return "N";

// For leaf nodes, return its value in string.


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

let curr = root.data.toString();

// Process the left and right subtree.


let left = dupSubRecur(root.left, s, ans);
let right = dupSubRecur(root.right, s, ans);

// If the node is parent to 2


// leaf nodes, or 1 leaf node and 1
// null node, then concatenate the strings
if (left !== "" && right !== "") {
curr += '*' + left + '*' + right;
} else {
return "";
}

// If this subtree string is already


// present in set, set ans to 1.
if (s.has(curr)) {
ans[0] = 1;
} else {
s.add(curr);
}

return "";
}

function dupSub(root) {
let ans = [0];
let s = new Set();

dupSubRecur(root, s, ans);

return ans[0];
https://www.geeksforgeeks.org/check-binary-tree-contains-duplicate-subtrees-size-2/?ref=lbp 5/6
3/30/25, 4:24 PM Check if a Binary Tree contains duplicate subtrees of size 2 or more | GeeksforGeeks
175
}

// A
// / \
// B C
// / \ \
// D E B
// / \
// D E
let root = new Node('A');
root.left = new Node('B');
root.right = new Node('C');
root.left.left = new Node('D');
root.left.right = new Node('E');
root.right.right = new Node('B');
root.right.right.right = new Node('E');
root.right.right.left = new Node('D');

console.log(dupSub(root) ? "True" : "False");

Output

True

https://www.geeksforgeeks.org/check-binary-tree-contains-duplicate-subtrees-size-2/?ref=lbp 6/6
3/30/25, 4:24 PM Check if two trees are Mirror | GeeksforGeeks
176

Check if two trees are Mirror


Last Updated : 24 Sep, 2024

Given two Binary Trees, the task is to check if two trees are mirror of
each other or not. For two trees ‘a’ and ‘b’ to be mirror images, the
following three conditions must be true:

1. Their root node’s key must be same


2. Left subtree of root of ‘a’ and right subtree root of ‘b’ are mirror.
3. Right subtree of ‘a’ and left subtree of ‘b’ are mirror.

Example:

Input:

Output: True
Explanation: Both trees are mirror images of each other, so
output is True

Input:

https://www.geeksforgeeks.org/check-if-two-trees-are-mirror/?ref=lbp 1/4
3/30/25, 4:24 PM Check if two trees are Mirror | GeeksforGeeks
177

Output: False
Explanation: Since both trees are not mirror images of each
other, the output is False.

Table of Content
[Expected Approach – 1] Recursive Approach – O(n) Time and O(h)
Space
[Expected Approach – 2] Iterative Approach – O(n) Time and O(n)
Space

[Expected Approach – 1] Recursive Approach – O(n) Time and


O(h) Space

The idea is to check if two binary trees are mirrors of each other
by comparing their structure and node values. We recursively
verify if the root nodes of both trees have the same value, then
check if the left subtree is a mirror of the right subtree. If both
trees are empty, they are considered mirrors; if one is empty and
the other is not, they are not mirrors. This approach ensures that
the trees are symmetric with respect to their root.

Below is implementation of above approach:

C++ C Java Python C# JavaScript

// Recursive JavaScript function to check if two


// roots are mirror images of each other
https://www.geeksforgeeks.org/check-if-two-trees-are-mirror/?ref=lbp 2/4
3/30/25, 4:24 PM Check if two trees are Mirror | GeeksforGeeks
178
class Node {
constructor(val) {
this.data = val;
this.left = null;
this.right = null;
}
}

// Function to check if two roots are mirror images


function areMirrors(root1, root2) {

// If both roots are empty, they are mirrors


if (root1 === null && root2 === null) {
return true;
}

// If only one root is empty, they are not mirrors


if (root1 === null || root2 === null) {
return false;
}

// Check if the root data is the same and


// if the left subroot of root1 is a mirror
// of the right subroot of root2 and vice versa
return (root1.data === root2.data) &&
areMirrors(root1.left, root2.right) &&
areMirrors(root1.right, root2.left);
}

// Representation of input binary tree 1


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

// Representation of input binary tree 2 (mirror)


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

if (areMirrors(root1, root2)) {
console.log("true");
}
else {

https://www.geeksforgeeks.org/check-if-two-trees-are-mirror/?ref=lbp 3/4
3/30/25, 4:24 PM Check if two trees are Mirror | GeeksforGeeks
179
console.log("false");
}

Output

true

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


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

[Expected Approach – 2] Iterative Approach – O(n) Time and


O(n) Space

The idea is to check if two binary trees are mirrors using two
stacks to simulate recursion. Nodes from each tree are pushed
onto the stacks in a way that compares the left subtree of one
tree with the right subtree of the other, and vice versa. This
approach systematically compares nodes while maintaining their
mirrored structure, ensuring the trees are symmetric relative to
their root. Please refer to Iterative method to check if two trees
are mirror of each other for implementation.

https://www.geeksforgeeks.org/check-if-two-trees-are-mirror/?ref=lbp 4/4
3/30/25, 4:25 PM Foldable Binary Trees | GeeksforGeeks
180

Foldable Binary Trees


Last Updated : 06 Nov, 2024

Given a binary tree, the task is to find out if the tree can be folded or
not. A tree can be folded if the left and right subtrees of the tree are
structure-wise mirror images of each other. An empty tree is
considered foldable.

Examples:

Input:

Output: True
Explanation: The above tree can be folded as left and right
subtrees of the tree are structure-wise mirror images of each
other.

Input:

https://www.geeksforgeeks.org/foldable-binary-trees/?ref=lbp 1/7
3/30/25, 4:25 PM Foldable Binary Trees | GeeksforGeeks
181

Output: False
Explanation: The above tree cannot be folded as left and right
subtrees of the tree are not structure-wise mirror images of each
other.

Table of Content
[Expected Approach – 1] By Changing Left Subtree to its Mirror –
O(n) Time and O(h) Space
[Expected Approach – 2] By Comparing Subtree Nodes Recursively
– O(n) Time and O(h) Space
[Expected Approach – 3] Using Breadth first Search – O(n) Time
and O(n) Space

[Expected Approach – 1] By Changing Left Subtree to its Mirror


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

The idea is to change the left subtree to its mirror then compare
the left subtree with the right subtree. First, convert the left
subtree to its mirror image (for each node, swap its left and right
nodes). Then compare the structure of left subtree and right
subtree and store the result. Revert the left subtree and return
the result.

C++ C Java Python C# JavaScript

// JavaScript program to check foldable binary tree


https://www.geeksforgeeks.org/foldable-binary-trees/?ref=lbp 2/7
3/30/25, 4:25 PM Foldable Binary Trees | GeeksforGeeks
182
class Node {
constructor(x) {
this.data = x;
this.left = null;
this.right = null;
}
}

// Function to convert subtree


// into its mirror
function mirror(root) {
if (root === null) return;

// Recursively process the left


// and right subtrees.
mirror(root.left);
mirror(root.right);

// swap the left and right nodes.


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

// function to check if two trees have


// same structure
function isStructSame(a, b) {

// If both subtrees are null, return


// true.
if (a === null && b === null)
return true;

// If one of the subtrees is null,


// return false.
if (a === null || b === null)
return false;

// check left and right subtree.


return isStructSame(a.left, b.left)
&&
isStructSame(a.right, b.right);
}

// Function to check if a tree is foldable.


function isFoldable(root) {
if (root === null)
return true;

// Convert left subtree into


// its mirror.
mirror(root.left);

// Compare the left subtree


// and right subtree.
let ans = isStructSame(root.left, root.right);

// Revert the left subtree.

https://www.geeksforgeeks.org/foldable-binary-trees/?ref=lbp 3/7
3/30/25, 4:25 PM Foldable Binary Trees | GeeksforGeeks
183
mirror(root.left);

return ans;
}

// The constructed binary tree is


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

if (isFoldable(root)) {
console.log("True");
} else {
console.log("False");
}

Output

True

[Expected Approach – 2] By Comparing Subtree Nodes


Recursively – O(n) Time and O(h) Space

The idea is to recursively check if the left and right subtree are
mirror or not. For each node a (of left subtree) and b (of right
subtree), recursively compare the left subtree of a with right
subtree of b and compare the right subtree of a with left
subtree of b. If both are mirror structures, return true. Otherwise,
return false.

C++ C Java Python C# JavaScript

// JavaScript program to check foldable binary tree

class Node {
constructor(x) {
this.data = x;
this.left = null;
this.right = null;
}
}
https://www.geeksforgeeks.org/foldable-binary-trees/?ref=lbp 4/7
3/30/25, 4:25 PM Foldable Binary Trees | GeeksforGeeks
184
// function to check if two trees are
// mirrors
function isFoldableRecur(a, b) {

// If both subtrees are null, return


// true.
if (a === null && b === null)
return true;

// If one of the subtrees is null,


// return false.
if (a === null || b === null)
return false;

// Compare left subtree of tree 'a' with


// right subtree of tree 'b' and compare
// right subtree of tree 'a' with left
// subtree of tree 'b'.
return isFoldableRecur(a.left, b.right)
&& isFoldableRecur(a.right, b.left);
}

// Function to check if a tree is foldable.


function isFoldable(root) {
if (root === null)
return true;

return isFoldableRecur(root.left, root.right);


}

// The constructed binary tree is


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

if (isFoldable(root)) {
console.log("True");
} else {
console.log("False");
}

Output

True

https://www.geeksforgeeks.org/foldable-binary-trees/?ref=lbp 5/7
3/30/25, 4:25 PM Foldable Binary Trees | GeeksforGeeks
185
[Expected Approach – 3] Using Breadth first Search – O(n)
Time and O(n) Space

The idea is to use Queue for traversing the tree and using the
BFS approach. Push the left node and right node of the root into
a queue. While queue is not empty, pop two nodes, a (left
subtree node) and b (right subtree node). If both are null nodes,
continue. If one of them is null, return false. Push the left node of
a with the right node of b, and push the right node of a with the
left node of b. If queue becomes empty, return true.

C++ Java Python C# JavaScript

// JavaScript program to check foldable


// binary tree

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

// Function to check if a tree is foldable.


function isFoldable(root) {
if (root === null)
return true;

let q = [];
q.push(root.left);
q.push(root.right);

while (q.length) {
let a = q.shift();
let b = q.shift();

// If both subtrees are null, continue.


if (a === null && b === null)
continue;

// If one of the subtrees is null,


// return false.
if (a === null || b === null)
return false;

// Push left node of a and right


// node of b.
q.push(a.left);
q.push(b.right);

https://www.geeksforgeeks.org/foldable-binary-trees/?ref=lbp 6/7
3/30/25, 4:25 PM Foldable Binary Trees | GeeksforGeeks
186
// Push right node of a and left
// node of b.
q.push(a.right);
q.push(b.left);
}

return true;
}

// The constructed binary tree is


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

if (isFoldable(root)) {
console.log("True");
} else {
console.log("False");
}

Output

True

https://www.geeksforgeeks.org/foldable-binary-trees/?ref=lbp 7/7
3/30/25, 4:25 PM Symmetric Tree (Mirror Image of itself) | GeeksforGeeks
187

Symmetric Tree (Mirror Image of itself)


Last Updated : 21 Jan, 2025

Given a binary tree, the task is to check whether it is a mirror of itself.

Example:

Input:

Output: True
Explanation: As the left and right half of the above tree is mirror
image, tree is symmetric.

Input:

https://www.geeksforgeeks.org/symmetric-tree-tree-which-is-mirror-image-of-itself/?ref=lbp 1/6
3/30/25, 4:25 PM Symmetric Tree (Mirror Image of itself) | GeeksforGeeks
188

Output: False
Explanation: As the left and right half of the above tree is not
the mirror image, tree is not symmetric.

Table of Content
[Approach – 1] Using Recursion – O(n) Time and O(h) Space
[Approach – 2] Using Stack – O(n) Time and O(h) Space
[Approach – 3] Using Queue – O(n) Time and O(n) Space

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

The idea is to recursively compare the left and right subtrees of


the root. For the tree to be symmetric, the root values of the left
and right subtrees must match, and their corresponding children
must also be mirrors.

C++ C Java Python C# JavaScript

// JavaScript program to check if a given


// Binary Tree is symmetric

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

https://www.geeksforgeeks.org/symmetric-tree-tree-which-is-mirror-image-of-itself/?ref=lbp 2/6
3/30/25, 4:25 PM Symmetric Tree (Mirror Image of itself) | GeeksforGeeks
189
// Recursive helper function to check if two subtrees are mirror images
function isMirror(leftSub, rightSub) {
// Both are null, so they are mirror images
if (leftSub === null && rightSub === null)
return true;

// One of them is null, so they aren't mirror images


if (leftSub === null || rightSub === null || leftSub.data !==
rightSub.data)
return false;

// Check if the subtrees are mirrors


return isMirror(leftSub.left, rightSub.right) &&
isMirror(leftSub.right, rightSub.left);
}

function isSymmetric(root) {
// If tree is empty, it's symmetric
if (root === null)
return true;

// Check if the left and right subtrees are mirrors of each other
return isMirror(root.left, root.right);
}

// Creating a sample symmetric binary tree


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

console.log(isSymmetric(root) ? "true" : "false");

Output

true

[Approach – 2] Using Stack – O(n) Time and O(h) Space

The idea is to use two stack to check if a binary tree is


symmetric. One stack is for the left side of the tree, and the
other is for the right side. By comparing nodes from both stack
at each level, we can check if the left and right sides are mirror
images of each other.

https://www.geeksforgeeks.org/symmetric-tree-tree-which-is-mirror-image-of-itself/?ref=lbp 3/6
3/30/25, 4:25 PM Symmetric Tree (Mirror Image of itself) | GeeksforGeeks
190

Step-by-step implementation:

Create a two stacks, say s1 and s2 and push the left child of the
root node in s1 and right child of the root node into s2.
While both the stack are not empty, repeat the following steps:
Pop two nodes from the stack, say node1 and node2.
If both node1 and node2 are null, continue to the next
iteration.
If one of the nodes is null and the other is not, return false
as it is not a mirror.
If both nodes are not null, compare their values. If they are
not equal, return false.
Push the left child of node1 and the right child of node2
onto the stack.
Push the right child of node1 and the left child of node2
onto the stack.
If the loop completes successfully without returning false, return
true as it is a mirror.

C++ Java Python C# JavaScript

// JavaScript program to check if a


// given Binary Tree is symmetric

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

// Function to check if the binary tree is symmetric


function isSymmetric(root) {
if (root === null) {
return true;
}

// Two stacks to store nodes for comparison


let s1 = [];
let s2 = [];

// Initialize the stacks with the


// left and right subtrees
https://www.geeksforgeeks.org/symmetric-tree-tree-which-is-mirror-image-of-itself/?ref=lbp 4/6
3/30/25, 4:25 PM Symmetric Tree (Mirror Image of itself) | GeeksforGeeks
191
s1.push(root.left);
s2.push(root.right);

while (s1.length > 0 && s2.length > 0) {

// Get the current pair of nodes


let node1 = s1.pop();
let node2 = s2.pop();

// If both nodes are null, continue to the next pair


if (node1 === null && node2 === null) {
continue;
}

// If one node is null and the other is not,


// or the nodes' data do not match
// then the tree is not symmetric
if (node1 === null || node2 === null
|| node1.data !== node2.data) {
return false;
}

// Push children of node1 and node2 in opposite order


// Push left child of node1 and right child of node2
s1.push(node1.left);
s2.push(node2.right);

// Push right child of node1 and left child of node2


s1.push(node1.right);
s2.push(node2.left);
}

// If both stacks are empty, the tree is symmetric


return s1.length === 0 && s2.length === 0;
}

// Creating a sample symmetric binary tree


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

console.log(isSymmetric(root));

Output

true

https://www.geeksforgeeks.org/symmetric-tree-tree-which-is-mirror-image-of-itself/?ref=lbp 5/6
3/30/25, 4:25 PM Symmetric Tree (Mirror Image of itself) | GeeksforGeeks
192
[Approach – 3] Using Queue – O(n) Time and O(n) Space

The basic idea is to check if the left and right subtrees of the root
node are mirror images of each other. To do this, we perform a
level-order traversal of the binary tree using a queue. Initially,
we push the root node into the queue twice. We dequeue two
nodes at a time from the front of the queue and check if they are
mirror images of each other. Please refer to Check for Symmetric
Binary Tree (Iterative Approach Using Queue) for
implementation.

https://www.geeksforgeeks.org/symmetric-tree-tree-which-is-mirror-image-of-itself/?ref=lbp 6/6
3/30/25, 4:25 PM Program to Determine if given Two Trees are Identical or not | GeeksforGeeks
193

Program to Determine if given Two Trees are


Identical or not
Last Updated : 24 Sep, 2024

Given two binary trees, the task is to find if both of them are identical
or not. Two trees are identical when they have the same data and the
arrangement of data is also the same.

Examples:

Input:

Output: Yes
Explanation: Trees are identical.

Input:

https://www.geeksforgeeks.org/write-c-code-to-determine-if-two-trees-are-identical/?ref=lbp 1/10
3/30/25, 4:25 PM Program to Determine if given Two Trees are Identical or not | GeeksforGeeks
194

Output: No
Explanation: Trees are not identical.

Table of Content
[Expected Approach – 1] Using DFS – O(n) Time and O(n) Space
[Expected Approach – 2] Using Level Order Traversal (BFS) – O(n)
Time and O(n) Space
[Expected Approach – 3] Using Morris Traversal – O(n) Time and
O(1) Space

[Expected Approach – 1] Using DFS – O(n) Time and O(n)


Space

The idea is to compare the root nodes’ data and recursively


verify that their left and right subtrees are identical. Both trees
must have the same structure and data at each corresponding
node.

Follow the given steps to solve the problem:

If both trees are empty then return 1 (Base case)


Else, If both trees are non-empty
Check data of the root nodes (r1->data == r2->data)
Check left subtrees recursively
Check right subtrees recursively
https://www.geeksforgeeks.org/write-c-code-to-determine-if-two-trees-are-identical/?ref=lbp 2/10
3/30/25, 4:25 PM Program to Determine if given Two Trees are Identical or not | GeeksforGeeks
195
If the above three statements are true then return 1
Else return 0 (one is empty and the other is not)

Below is the implementation of the above approach:

C++ C Java Python C# JavaScript

// Javascript program to see if two trees are identical


// using DFS
class Node {
constructor(val) {
this.data = val;
this.left = null;
this.right = null;
}
}

// Function to check if two trees are identical


function isIdentical(r1, r2) {

// If both trees are empty, they are identical


if (r1 === null && r2 === null)
return true;

// If only one tree is empty, they are not identical


if (r1 === null || r2 === null)
return false;

// Check if the root data is the same and


// recursively check for the left and right subtrees
return (r1.data === r2.data &&
isIdentical(r1.left, r2.left) &&
isIdentical(r1.right, r2.right));
}

// Representation of input binary tree 1


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

// Representation of input binary tree 2


// 1
// / \
// 2 3
// /
// 4
let r2 = new Node(1);
r2.left = new Node(2);
r2.right = new Node(3);
r2.left.left = new Node(4);
https://www.geeksforgeeks.org/write-c-code-to-determine-if-two-trees-are-identical/?ref=lbp 3/10
3/30/25, 4:25 PM Program to Determine if given Two Trees are Identical or not | GeeksforGeeks
196
if (isIdentical(r1, r2)) {
console.log("Yes");
}
else {
console.log("No");
}

Output

Yes

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


of the two trees, as each node is visited once.
Auxiliary Space: O(h), where h is the height of the trees, due to the
recursive call stack.

[Expected Approach – 2] Using Level Order Traversal (BFS) –


O(n) Time and O(n) Space

The idea is to use level order traversal with two queues to


compare the structure and data of two trees. By enqueuing
nodes from both trees simultaneously, we can compare
corresponding nodes at each level. If nodes at any level differ in
data or structure, or if one tree has nodes where the other does
not, the trees are not identical. This approach ensures that the
trees are identical in both structure and node values if all nodes
match and the queues are empty at the end.

Follow the below steps to implement the above idea:

Enqueue the root nodes of both trees into a queue.


While the queue is not empty, dequeue the front nodes of both
trees and compare their values.
If the values are not equal, return false.
If the values are equal, enqueue the left and right child nodes of
both trees, if they exist, into the queue.
Repeat steps 2-4 until either the queue becomes empty or we find
two nodes with unequal values.

https://www.geeksforgeeks.org/write-c-code-to-determine-if-two-trees-are-identical/?ref=lbp 4/10
3/30/25, 4:25 PM Program to Determine if given Two Trees are Identical or not | GeeksforGeeks
197
If the queue becomes empty and we have not found any nodes with
unequal values, return true indicating that the trees are identical.

Below is the implementation of the above approach:

C++ Java Python C# JavaScript

// Javascript program to see if two trees are identical


// using Level Order Traversal(BFS)
class Node {
constructor(val) {
this.data = val;
this.left = null;
this.right = null;
}
}

// Function to check if two trees are identical


// using level-order traversal
function isIdentical(r1, r2) {

// If both trees are empty, they are identical


if (r1 === null && r2 === null)
return true;

// If one tree is empty and the other is not


if (r1 === null || r2 === null)
return false;

// Queues for level-order traversal


let queue1 = [r1];
let queue2 = [r2];

// Perform level-order traversal for both trees


while (queue1.length > 0 && queue2.length > 0) {
let node1 = queue1.shift();
let node2 = queue2.shift();

// Check if the current nodes' data are not equal


if (node1.data !== node2.data)
return false;

// Check left children


if (node1.left && node2.left) {
queue1.push(node1.left);
queue2.push(node2.left);
}
else if (node1.left || node2.left) {
return false;
}

// Check right children


if (node1.right && node2.right) {
queue1.push(node1.right);
queue2.push(node2.right);
}
https://www.geeksforgeeks.org/write-c-code-to-determine-if-two-trees-are-identical/?ref=lbp 5/10
3/30/25, 4:25 PM Program to Determine if given Two Trees are Identical or not | GeeksforGeeks
198
else if (node1.right || node2.right) {
return false;
}
}

// Both queues should be empty if trees are identical


return queue1.length === 0 && queue2.length === 0;
}

// Representation of input binary tree 1


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

// Representation of input binary tree 2


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

if (isIdentical(r1, r2)) {
console.log("Yes");
}
else {
console.log("No");
}

Output

Yes

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


of the two trees, as each node is visited once.
Auxiliary Space: O(w), where w is the maximum width of the trees at
any level, due to the space required for the queues.

[Expected Approach – 3] Using Morris Traversal – O(n) Time


and O(1) Space

https://www.geeksforgeeks.org/write-c-code-to-determine-if-two-trees-are-identical/?ref=lbp 6/10
3/30/25, 4:25 PM Program to Determine if given Two Trees are Identical or not | GeeksforGeeks
199
The idea is to use Morris traversal for comparing two trees,
traverse both trees simultaneously by starting at their roots. For
each node, if the left subtree exists, find the rightmost node in
the left subtree (the predecessor) and create a temporary link
back to the current node. Then, move to the left subtree. If no left
subtree exists, compare the current nodes of both trees and
move to the right subtree. At each step, compare the values of
the corresponding nodes and ensure the structure matches. If at
any point the values or structure differ, the trees are not
identical. The process continues until both trees are fully
traversed, and any temporary links created are removed. If no
mismatches are found, the trees are identical.

Follow the steps to implement the above idea:

Check if both trees are empty. If they are, return true. If only one of
them is empty, return false.
Perform the Morris traversal for in-order traversal of both trees
simultaneously. At each step, compare the nodes visited in both
trees.
If at any step, the nodes visited in both trees are not equal, return
false.
If we reach the end of both trees simultaneously (i.e., both nodes
are NULL), return true.

Below is the implementation of the above approach:

C++ C Java Python C# JavaScript

// Javascript program to see if two trees are identical


// using Morris Traversal
class Node {
constructor(val) {
this.data = val;
this.left = null;
this.right = null;
}
}

// Function to check if two trees are identical


// using Morris traversal
function isIdentical(r1, r2) {

// Check if both trees are empty


if (r1 === null && r2 === null) {
https://www.geeksforgeeks.org/write-c-code-to-determine-if-two-trees-are-identical/?ref=lbp 7/10
3/30/25, 4:25 PM Program to Determine if given Two Trees are Identical or not | GeeksforGeeks
200
return true;
}

// Check if one tree is empty and the other is not


if (r1 === null || r2 === null) {
return false;
}

// Morris traversal to compare both trees


while (r1 !== null && r2 !== null) {

// Compare the data of both current nodes


if (r1.data !== r2.data) {
return false;
}

// Morris traversal for the first tree (r1)


if (r1.left === null) {

// Move to the right child if no left child


r1 = r1.right;
}
else {

// Find the inorder predecessor of r1


let pre = r1.left;
while (pre.right !== null && pre.right !== r1) {
pre = pre.right;
}

// Set the temporary link to r1


if (pre.right === null) {
pre.right = r1;
r1 = r1.left;
}

// Remove the temporary link and move to right


else {
pre.right = null;
r1 = r1.right;
}
}

// Morris traversal for the second tree (r2)


if (r2.left === null) {

// Move to the right child if no left child


r2 = r2.right;
}
else {

// Find the inorder predecessor of r2


let pre = r2.left;
while (pre.right !== null && pre.right !== r2) {
pre = pre.right;
}

// Set the temporary link to r2


if (pre.right === null) {

https://www.geeksforgeeks.org/write-c-code-to-determine-if-two-trees-are-identical/?ref=lbp 8/10
3/30/25, 4:25 PM Program to Determine if given Two Trees are Identical or not | GeeksforGeeks
201
pre.right = r2;
r2 = r2.left;
}

// Remove the temporary link and move to right


else {
pre.right = null;
r2 = r2.right;
}
}
}

// Both trees are identical if both are null at end


return r1 === null && r2 === null;
}

// Representation of input binary tree 1


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

// Representation of input binary tree 2


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

if (isIdentical(r1, r2)) {
console.log("Yes");
}
else {
console.log("No");
}

Output

Yes

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


of the two trees, as each node is visited once.
Auxiliary Space: O(1), Morris traversal modifies the tree temporarily

https://www.geeksforgeeks.org/write-c-code-to-determine-if-two-trees-are-identical/?ref=lbp 9/10
3/30/25, 4:25 PM Program to Determine if given Two Trees are Identical or not | GeeksforGeeks
202
by establishing “threads” to traverse nodes without using recursion or
a stack.

https://www.geeksforgeeks.org/write-c-code-to-determine-if-two-trees-are-identical/?ref=lbp 10/10
3/30/25, 4:25 PM Subtree with given sum in a Binary Tree | GeeksforGeeks
203

Subtree with given sum in a Binary Tree


Last Updated : 29 Sep, 2024

You are given a binary tree and a given sum. The task is to check if
there exists a subtree whose sum of all nodes is equal to the given
sum.

Examples:

Input : key = 11

Output: True
Explanation: sum of all nodes of subtree {2, 4, 5} = 11.

Input : key = 6

https://www.geeksforgeeks.org/subtree-given-sum-binary-tree/?ref=lbp 1/6
3/30/25, 4:25 PM Subtree with given sum in a Binary Tree | GeeksforGeeks
204

Output: False
Explanation: No subtree whose sum of all nodes = 6.

Table of Content
[Expected Approach – 1] Using Recursion – O(n) Time and O(h)
Space
[Expected Approach – 2] Using HashMap- O(n) Time and O(n)
Space

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


Space

The idea is to traverse the binary tree recursively, calculating the


sum of the subtree rooted at each node. At each node, we
compute the sum of its left and right subtrees and add the
node’s value itself. If the sum of any subtree matches the given
key sum, we mark it as found. We use a helper function
subtreeSum() to compute the sum of each subtree and a flag
foundSum to track if the key sum is found.

Below is the implementation of the above approach:

C++ C Java Python C# JavaScript

// JavaScript program to find if there is a subtree with


// given sum

https://www.geeksforgeeks.org/subtree-given-sum-binary-tree/?ref=lbp 2/6
3/30/25, 4:25 PM Subtree with given sum in a Binary Tree | GeeksforGeeks
205
// Node definition for a binary tree
class Node {
constructor(x) {
this.data = x;
this.left = null;
this.right = null;
}
}

// Function to calculate the sum of the subtree


// rooted at the given node
function subtreeSum(root, foundSum, target) {

// Base case: If the node is NULL, return 0


if (root === null)
return 0;

// Calculate the sum of the current subtree


let currentSum = root.data +
subtreeSum(root.left, foundSum, target) +
subtreeSum(root.right, foundSum, target);

// If the current subtree sum matches the target,


// set foundSum to true
if (currentSum === target) {
foundSum.value = true;
}

// Return the current subtree sum


return currentSum;
}

// Function to check if there is a subtree with the given sum


function hasSubtreeWithGivenSum(root, sum) {
let foundSum = { value: false };

// Traverse the tree and check for the target sum


subtreeSum(root, foundSum, sum);

// Return true if a subtree with the given sum was found


return foundSum.value;
}

// Creating the given binary tree


// 1
// / \
// 3 6
// / \ /
// 5 9 8

let root = new Node(1);


root.left = new Node(3);
root.right = new Node(6);
root.left.left = new Node(5);
root.left.right = new Node(9);
root.right.left = new Node(8);

console.log(hasSubtreeWithGivenSum(root, 17));

https://www.geeksforgeeks.org/subtree-given-sum-binary-tree/?ref=lbp 3/6
3/30/25, 4:25 PM Subtree with given sum in a Binary Tree | GeeksforGeeks
206

Output

True

Time Complexity: O(n), As we are visiting every node once.


Auxiliary space: O(h), here h is the height of the tree and the extra
space is used due to the recursion call stack.

[Expected Approach – 2] Using HashMap- O(n) Time and O(n)


Space

The idea is to use an iterative depth-first traversal of the binary


tree while maintaining a running sum of the node values
encountered so far. We will use a hashmap to keep track of the
prefix sums encountered during the traversal.

Follow the steps below to solve the problem:

Start with the root node of the binary tree and push it onto the
stack.
While the stack is not empty, repeatedly:
Pop the top node from the stack.
Update the running sum by adding the current node’s
value.
Check if (current sum – target sum) exists in the
prefixSumMap. If it does, it means there is a subtree with
the required sum.
Add or update the current running sum in the
prefixSumMap to keep track of sums encountered.
Push the right and left children of the current node onto
the stack (if they exist) to continue the traversal.

Below is the implementation of the above approach:

C++ Java Python C# JavaScript

// JavaScript program to find if there is a subtree with


https://www.geeksforgeeks.org/subtree-given-sum-binary-tree/?ref=lbp 4/6
3/30/25, 4:25 PM
p p g f Subtree with given sum in a Binary Tree | GeeksforGeeks
f 207
// given sum

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

// Function to check if there is a subtree with the given sum


function hasSubtreeWithGivenSum(root, target) {
if (root === null) return false;

// Map to store the prefix sums


const prefixSumMap = new Map();
prefixSumMap.set(0, 1);

let sum = 0;
const stack = [root];

// Iterative depth-first traversal


while (stack.length > 0) {
const curr = stack.pop();

// Update the running sum with the current node's value


sum += curr.val;

// Check if we have encountered (sum - target) before


if (prefixSumMap.has(sum - target)) {
return true;
}

// Add the current running sum to the map


prefixSumMap.set(sum, 1);

// Traverse the right and left children


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

// If no subtree with the given sum is found


return false;
}

// Creating the given binary tree


// 1
// / \
// 3 6
// / \ /
// 5 9 8

const root = new Node(1);


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

https://www.geeksforgeeks.org/subtree-given-sum-binary-tree/?ref=lbp 5/6
3/30/25, 4:25 PM Subtree with given sum in a Binary Tree | GeeksforGeeks
208
root.left.left = new Node(5);
root.left.right = new Node(9);
root.right.left = new Node(8);

console.log(hasSubtreeWithGivenSum(root, 17));

Output

True

Time complexity : O(n), As we are visiting every node once.


Auxiliary Space : O(n)

https://www.geeksforgeeks.org/subtree-given-sum-binary-tree/?ref=lbp 6/6
3/30/25, 4:25 PM Succinct Encoding of Binary Tree | GeeksforGeeks
209

Succinct Encoding of Binary Tree


Last Updated : 28 Oct, 2024

A succinct encoding of Binary Tree takes close to the minimum


possible space. The number of structurally different binary trees on n
nodes is n’th Catalan number. For large n, this is about 4n; thus we
need at least about log2 4n = 2n bits to encode it. A succinct binary
tree therefore would occupy 2n + O(n) bits.

One simple representation that meets this bound is to visit the nodes
of the tree in preorder, outputting “1” for a not-null node and “0” for a
null node. If the tree contains data, we can simply simultaneously
store it in a consecutive array in preorder.

Example:

Input:

Output: 1 1 0 0 1 0 1 0 0
Explanation: 1 indicates data and 0 indicates NULL.

Table of Content
https://www.geeksforgeeks.org/succinct-encoding-of-binary-tree/?ref=lbp 1/4
3/30/25, 4:25 PM Succinct Encoding of Binary Tree | GeeksforGeeks
210
Approach for encoding binary tree – O(n) Time and O(n) Space
Approach for decoding binary tree – O(n) Time and O(n) Space

Approach for encoding binary tree – O(n) Time and O(n) Space

The idea is to perform pre-order traversal of the binary tree. If


the node is null, then append ‘0’ to the string. Otherwise append
‘1’ to the string and push the node value into a data array.
Return the string and data array.

Below is the implementation of above approach:

C++ Java Python C# JavaScript

// JavaScript program to encode a


// binary tree.

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

// Recursive pre-order function to


// encode a binary tree.
function encodeTreeRecur(root, s, arr) {

// For null nodes


if (root === null) {
s.push('0');
return;
}

s.push('1');

// Store pre-order in array.


arr.push(root.data);

// Apply pre-order to left and


// right subtree.
encodeTreeRecur(root.left, s, arr);
encodeTreeRecur(root.right, s, arr);
}

function encodeTree(root) {
let s = [];
let arr = [];

encodeTreeRecur(root, s, arr);
https://www.geeksforgeeks.org/succinct-encoding-of-binary-tree/?ref=lbp 2/4
3/30/25, 4:25 PM Succinct Encoding of Binary Tree | GeeksforGeeks
211
return [s.join(''), arr];
}

// Binary tree
// 10
// / \
// 20 30
// / \ \
// 40 50 70
let root = new Node(10);
root.left = new Node(20);
root.right = new Node(30);
root.left.left = new Node(40);
root.left.right = new Node(50);
root.right.right = new Node(70);

const ans = encodeTree(root);

console.log(ans[0]);
console.log(ans[1].join(" "));

Output

1110010010100
10 20 40 50 30 70

Approach for decoding binary tree – O(n) Time and O(n) Space

The idea is to perform pre-order traversal of the string. If the


current character is ‘0’, return null. Otherwise create a new node
with value equal to current element of the data array. Return the
root node.

Below is the implementation of the above approach:

C++ Java Python C# JavaScript

// JavaScript program to decode a


// binary tree.

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

https://www.geeksforgeeks.org/succinct-encoding-of-binary-tree/?ref=lbp 3/4
3/30/25, 4:25 PM Succinct Encoding of Binary Tree | GeeksforGeeks
212
// Recursive pre-order function to
// decode a binary tree.
function decodeTreeRecur(i, s, j, arr) {

// if s[i]==0, return null node


if (s[i[0]] === '0') {
i[0]++;
return null;
}

// Create a new Node


const root = new Node(arr[j[0]++]);
i[0]++;

// Construct left and right subtree.


root.left = decodeTreeRecur(i, s, j, arr);
root.right = decodeTreeRecur(i, s, j, arr);

return root;
}

function decodeTree(s, arr) {


let i = [0];
let j = [0];
return decodeTreeRecur(i, s, j, arr);
}

function printInorder(root) {
if (root === null) return;
printInorder(root.left);
console.log(root.data);
printInorder(root.right);
}

let s = "1110010010100";
let arr = [10, 20, 40, 50, 30, 70];

let root = decodeTree(s, arr);


printInorder(root);

Output

40 20 50 10 30 70

https://www.geeksforgeeks.org/succinct-encoding-of-binary-tree/?ref=lbp 4/4
3/30/25, 4:26 PM Write a program to Calculate Size of a tree | Recursion | GeeksforGeeks
213

Write a program to Calculate Size of a tree |


Recursion
Last Updated : 25 Oct, 2024

Given a binary tree, the task is to find the size of the tree. The size of a
tree is the number of nodes present in the tree.

Examples:

Input:

Output: 6
Explanation: The number of nodes in the above binary tree is 6.

Approach:

The idea is to recursively calculate the size of tree. For each node
(starting from root node), calculate the size of left subtree and
right subtree and return the size of current subtree (size of left
subtree + size of right subtree + 1).

Below is the implementation of the above approach:


https://www.geeksforgeeks.org/write-a-c-program-to-calculate-size-of-a-tree/?ref=lbp 1/3
3/30/25, 4:26 PM Write a program to Calculate Size of a tree | Recursion | GeeksforGeeks
214
C++ C Java Python C# JavaScript

// JavaScript program to find the size


// of a binary tree.

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

// Recursive function to find the


// size of binary tree.
function getSize(root) {
if (root === null)
return 0;

// Find the size of left and right


// subtree.
let left = getSize(root.left);
let right = getSize(root.right);

// return the size of curr subtree.


return left + right + 1;
}

// Constructed binary tree is


// 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);

console.log(getSize(root));

Output

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


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

https://www.geeksforgeeks.org/write-a-c-program-to-calculate-size-of-a-tree/?ref=lbp 2/3
3/30/25, 4:26 PM Write a program to Calculate Size of a tree | Recursion | GeeksforGeeks
215

https://www.geeksforgeeks.org/write-a-c-program-to-calculate-size-of-a-tree/?ref=lbp 3/3
3/30/25, 4:26 PM Diameter of a Binary Tree | GeeksforGeeks
216

Diameter of a Binary Tree


Last Updated : 24 Jan, 2025

Given a binary tree, the task is to determine the diameter of the tree.
The diameter/width of a tree is defined as the number of edges on the
longest path between any two nodes.

Examples:

Input:

Output: 2
Explanation: The longest path has 2 edges (node 2 -> node 1 -
> node 3).

https://www.geeksforgeeks.org/diameter-of-a-binary-tree/?ref=lbp 1/5
3/30/25, 4:26 PM Diameter of a Binary Tree | GeeksforGeeks
217

Input:

Output: 4
Explanation: The longest path has 4 edges (node 3 -> node 8 ->
node 5 -> node 6 -> node 9).

https://www.geeksforgeeks.org/diameter-of-a-binary-tree/?ref=lbp 2/5
3/30/25, 4:26 PM Diameter of a Binary Tree | GeeksforGeeks
218

Table of Content
[Naive Approach] Using Top Down Recursion – O(n^2) Time and
O(h) Space
[Expected Approach] Using Bottom Up Recursive – O(n) Time and
O(h) Space

[Naive Approach] Using Top Down Recursion – O(n^2) Time


and O(h) Space

The idea is to recursively traverse the tree. For each node, find
the height of left subtree and right subtree and compare the
diameter (sum of height of left subtree + height of right subtree)
with the maximum diameter.

For implementation refer: Diameter of a Binary Tree using Top


Down Recursion

[Expected Approach] Using Bottom Up Recursive – O(n) Time


and O(h) Space

The idea is to optimize the above approach by calculating the


height in the same recursive function rather than calculating it
separately.

https://www.geeksforgeeks.org/diameter-of-a-binary-tree/?ref=lbp 3/5
3/30/25, 4:26 PM Diameter of a Binary Tree | GeeksforGeeks
219
Step by step approach:

Initialize a variable ans, which will store the diameter of the tree.
(initially set to 0).
Recursively traverse the binary tree. For each node, find the height
of the left and right subtree. Then compare the sum of (height of
left subtree + height of right subtree) with the ans variable. If it is
greater than ans, then update the value of ans.

C++ C Java Python C# JavaScript

// JavaScript program to find the diameter


// of a binary tree.

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

// Recursive function which finds the


// height of root and also calculates
// the diameter of the tree.
function diameterRecur(root, res) {

// Base case: tree is empty


if (root === null)
return 0;

// find the height of left and right subtree


// (it will also find of diameter for left
// and right subtree).
let lHeight = diameterRecur(root.left, res);
let rHeight = diameterRecur(root.right, res);

// Check if diameter of root is greater


// than res.
res.value = Math.max(res.value, lHeight + rHeight);

// return the height of current subtree.


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

// Function to get diameter of a binary tree


function diameter(root) {
let res = { value: 0 };
diameterRecur(root, res);
return res.value;
}

// Driver Code

https://www.geeksforgeeks.org/diameter-of-a-binary-tree/?ref=lbp 4/5
3/30/25, 4:26 PM Diameter of a Binary Tree | GeeksforGeeks
220
// Constructed binary tree is
// 5
// / \
// 8 6
// / \ /
// 3 7 9
let root = new Node(5);
root.left = new Node(8);
root.right = new Node(6);
root.left.left = new Node(3);
root.left.right = new Node(7);
root.right.left = new Node(9);

console.log(diameter(root));

Output

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


Auxiliary Space: O(h) due to recursive calls.

Related article:

Diameter of an N-ary tree

https://www.geeksforgeeks.org/diameter-of-a-binary-tree/?ref=lbp 5/5
3/30/25, 4:26 PM Level of a Node in Binary Tree | GeeksforGeeks
221

Level of a Node in Binary Tree


Last Updated : 29 Sep, 2024

Given a Binary Tree and a key, the task is to find the level of key in the
Binary Tree.

Examples:

Input : key = 4

Output: 3
Explanation: The level of the key in above binary tree is 3.

Input : key = 10

https://www.geeksforgeeks.org/get-level-of-a-node-in-a-binary-tree/?ref=lbp 1/5
3/30/25, 4:26 PM Level of a Node in Binary Tree | GeeksforGeeks
222

Output: -1
Explanation: Key is not present in the above Binary tree.

Table of Content
[Expected Approach – 1] Using Recursion – O(n) Time and O(h)
Space
[Expected Approach – 2] Using Level Order Traversal- O(n) Time
and O(n) Space

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


Space

The idea is to start from the root and level as 1. If the target
matches with root’s data, return level. Else recursively call for
left and right subtrees with level as level + 1.

Below is the implementation of the above approach:

C++ C Java Python C# JavaScript

// Javascript code to find level of a Node


// in Binary Tree

class Node {
constructor(val) {
this.data = val;
this.left = null;
this.right = null;
https://www.geeksforgeeks.org/get-level-of-a-node-in-a-binary-tree/?ref=lbp 2/5
3/30/25, 4:26 PM Level of a Node in Binary Tree | GeeksforGeeks
223
}
}

// Recursive function to find the level of the target key


function getLevel(root, target, level) {
if (root === null) {
return -1;
}

// If the target key matches the current node's


// data, return the level
if (root.data === target) {
return level;
}

// Recursively call for left and right subtrees


let leftLevel = getLevel(root.left, target, level + 1);
if (leftLevel !== -1) {
return leftLevel;
}

return getLevel(root.right, target, level + 1);


}

// Creating a sample binary tree:


// 1
// / \
// 2 3
// / \ / \
// 4 5 6 7
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);

const target = 5;
console.log(getLevel(root, target, 1));

Output

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


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

[Expected Approach – 2] Using Level Order Traversal- O(n)


Time and O(n) Space

https://www.geeksforgeeks.org/get-level-of-a-node-in-a-binary-tree/?ref=lbp 3/5
3/30/25, 4:26 PM Level of a Node in Binary Tree | GeeksforGeeks
224
The idea is to perform a level-order traversal and keep track of
the current level as we traverse the tree. If the key matches with
root’s data, return level.

C++ Java Python C# JavaScript

// Javascript code to find level of


// a Node in Binary Tree

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

// Function to find the level of the target key


function getLevel(root, target) {
if (root === null) {
return -1;
}

// Create a queue for level-order traversal


let q = [];
q.push(root);
let level = 1;

while (q.length > 0) {


let size = q.length;

// Process all nodes at the current level


for (let i = 0; i < size; i++) {
let curr = q.shift();

// Check if the current node matches the target


if (curr.data === target) {
return level;
}

// Push the left and right children to the queue


if (curr.left !== null) {
q.push(curr.left);
}
if (curr.right !== null) {
q.push(curr.right);
}
}

level++;
}

return -1;
}

https://www.geeksforgeeks.org/get-level-of-a-node-in-a-binary-tree/?ref=lbp 4/5
3/30/25, 4:26 PM Level of a Node in Binary Tree | GeeksforGeeks
225
// Creating the binary tree
// 1
// / \
// 2 3
// / \ / \
// 4 5 6 7
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);
root.right.left = new Node(6);
root.right.right = new Node(7);

let target = 5;
console.log(getLevel(root, target));

Output

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


tree.
Auxiliary Space: O(n)

https://www.geeksforgeeks.org/get-level-of-a-node-in-a-binary-tree/?ref=lbp 5/5
3/30/25, 10:21 PM Construct Complete Binary Tree from its Linked List Representation | GeeksforGeeks
226

Construct Complete Binary Tree from its Linked


List Representation
Last Updated : 19 Sep, 2024

Given the Linked List Representation of a Complete Binary Tree, the


task is to construct the complete binary tree. The complete binary tree
is represented as a linked list in a way where if the root node is stored
at position i, its left, and right children are stored at position 2*i+1,
and 2*i+2 respectively.

Examples:

Input: 1->2->3>4->5
Output:

Input: 10->12->15->25->30->36
Output:

https://www.geeksforgeeks.org/given-linked-list-representation-of-complete-tree-convert-it-to-linked-representation/?ref=lbp 1/5
3/30/25, 10:21 PM Construct Complete Binary Tree from its Linked List Representation | GeeksforGeeks
227

[Expected Approach] Using Level Order Traversal – O(n) Time


and O(n) Space:

We are mainly given level order traversal in sequential form.


Head of linked list is always the root of the tree. The first node
as root and that the next two nodes are left and right children of
root. So we know partial Binary Tree.

The idea is to do Level order traversal of the partially built


Binary Tree using queue and traverse the linked list at the same
time. At every step, we take the parent node from queue, make
next two nodes of linked list as children of the parent node, and
push the next two nodes to queue.

Below is the implementation of the above approach:

C++ Java Python C# JavaScript

// JavaScript program to create a Complete Binary tree


// from its Linked List Representation

// Linked list node class


class Lnode {
constructor(value) {
this.data = value;
this.next = null;
}
}

// Binary tree node class

https://www.geeksforgeeks.org/given-linked-list-representation-of-complete-tree-convert-it-to-linked-representation/?ref=lbp 2/5
3/30/25, 10:21 PM Construct Complete Binary Tree from its Linked List Representation | GeeksforGeeks
228
class Tnode {
constructor(value) {
this.data = value;
this.left = null;
this.right = null;
}
}

// Converts a given linked list representing a


// complete binary tree into the linked representation of a binary tree.
function convert(head) {
if (head === null) {
return null;
}

// Queue to store the parent nodes


let q = [];

// The first node is always the root node,


// and add it to the queue
let root = new Tnode(head.data);
q.push(root);

// Move the pointer to the next node


head = head.next;

// Until the end of the linked list is reached,


// do the following steps
while (head) {

// Take the parent node from the queue


// and remove it from the queue
let parent = q.shift();

let leftChild = null;


let rightChild = null;

// Create left child


if (head) {
leftChild = new Tnode(head.data);
q.push(leftChild);
head = head.next;
}

// Create right child


if (head) {
rightChild = new Tnode(head.data);
q.push(rightChild);
head = head.next;
}

// Assign the left and right


// children of the parent
parent.left = leftChild;
parent.right = rightChild;
}

return root;
}

https://www.geeksforgeeks.org/given-linked-list-representation-of-complete-tree-convert-it-to-linked-representation/?ref=lbp 3/5
3/30/25, 10:21 PM Construct Complete Binary Tree from its Linked List Representation | GeeksforGeeks
229
// Level Order Traversal of the binary tree
function levelOrderTraversal(root) {
if (root === null) {
return;
}

// Queue to hold nodes at each level


let q = [];
q.push(root);

while (q.length > 0) {


let currNode = q.shift();

// Print the current node's data


console.log(currNode.data + " ");

// Push the left and right children


// of the current node to the queue
if (currNode.left) {
q.push(currNode.left);
}
if (currNode.right) {
q.push(currNode.right);
}
}
}

// Create linked list : 10->12->15->25->30->36


let head = new Lnode(10);
head.next = new Lnode(12);
head.next.next = new Lnode(15);
head.next.next.next = new Lnode(25);
head.next.next.next.next = new Lnode(30);
head.next.next.next.next.next = new Lnode(36);

let root = convert(head);


levelOrderTraversal(root);

Output

10 12 15 25 30 36

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


Auxiliary Space: O(n), The queue stores at most n/2 nodes at any
point, since for every node processed, its children are added to the
queue. Therefore, the maximum space used by the queue is O(n).

https://www.geeksforgeeks.org/given-linked-list-representation-of-complete-tree-convert-it-to-linked-representation/?ref=lbp 4/5
3/30/25, 10:21 PM Construct Complete Binary Tree from its Linked List Representation | GeeksforGeeks
230

https://www.geeksforgeeks.org/given-linked-list-representation-of-complete-tree-convert-it-to-linked-representation/?ref=lbp 5/5
3/30/25, 10:19 PM Find all possible Binary Trees with given Inorder Traversal | GeeksforGeeks
231

Find all possible Binary Trees with given Inorder


Traversal
Last Updated : 20 Sep, 2024

Given an array that represents Inorder Traversal, the task is to find all
possible Binary Trees with the given inorder traversal and print their
preorder traversals.

Examples:

Input: inorder[] = {7, 5}


Output:
57
75

Input: inorder[] = {1, 2, 3}


Output:
123
132
213
312
321

https://www.geeksforgeeks.org/find-all-possible-trees-with-given-inorder-traversal/?ref=lbp 1/4
3/30/25, 10:19 PM Find all possible Binary Trees with given Inorder Traversal | GeeksforGeeks
232

Approach:

The idea is to generate all possible binary trees that can be


formed from a given inorder traversal by recursively selecting
each element as the root of the tree. Once a root is chosen, the
remaining elements are divided into two subarrays—one for the
left subtree and one for the right subtree. We then recursively
generate all possible left and right subtrees for that root and
combine them to form different binary trees.

Lets’s say, for an inorder traversal [1, 2, 3]:

We treat each element (1, 2, or 3) as the root.


For root 2, the left subtree will be [1] and the right subtree will be
[3]. Combine the trees formed from [1] and [3] with root 2 to
generate one of the possible trees.
Repeat this for every element being the root and recursively
generate subtrees.

Below is the implementation of the above approach:

C++ Java Python C# JavaScript

// JavaScript program to find binary tree with given inorder


// traversal

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

// Function to construct all possible binary trees with


// given inorder traversal

https://www.geeksforgeeks.org/find-all-possible-trees-with-given-inorder-traversal/?ref=lbp 2/4
3/30/25, 10:19 PM Find all possible Binary Trees with given Inorder Traversal | GeeksforGeeks
233
function getTrees(inorder, start, end) {
let trees = [];

// Base case:
// If start index is greater than end, return
// empty tree (null)
if (start > end) {
trees.push(null);
return trees;
}

// Iterate through all values in the array and construct


// left and right subtrees
for (let i = start; i <= end; ++i) {

// Generate all left subtrees


let leftTrees = getTrees(inorder, start, i - 1);

// Generate all right subtrees


let rightTrees = getTrees(inorder, i + 1, end);

// Combine each left and right subtree with the


// current root
for (let left of leftTrees) {
for (let right of rightTrees) {

// Make inorder[i] the root


let root = new Node(inorder[i]);
root.left = left;
root.right = right;
trees.push(root);
}
}
}

return trees;
}

function preorder(root) {
if (root !== null) {
console.log(root.data + " ");
preorder(root.left);
preorder(root.right);
}
}

let inorder = [ 1, 2, 3 ];
let n = inorder.length;

let trees = getTrees(inorder, 0, n - 1);

for (let tree of trees) {


preorder(tree);
console.log("\n");
}

Output
https://www.geeksforgeeks.org/find-all-possible-trees-with-given-inorder-traversal/?ref=lbp 3/4
3/30/25, 10:19 PM Find all possible Binary Trees with given Inorder Traversal | GeeksforGeeks
234
1 2 3
1 3 2
2 1 3
3 1 2
3 2 1

Time Complexity: O(n * Cn​), where Cn​is the Catalan number


Auxiliary Space: O(Cn​+ n), for storing trees and the recursion stack.

Related articles:

Program for nth Catalan Number


Construct all possible BSTs for keys 1 to N

https://www.geeksforgeeks.org/find-all-possible-trees-with-given-inorder-traversal/?ref=lbp 4/4
3/30/25, 10:20 PM Populate Inorder Successor for all nodes | GeeksforGeeks
235

Populate Inorder Successor for all nodes


Last Updated : 21 Dec, 2022

Given a Binary Tree where each node has the following structure,
write a function to populate the next pointer for all nodes. The next
pointer for every node should be set to point to in-order successor.

class Node
{

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

// This code is contributed by Shubham Singh

Initially, all next pointers have NULL values. Your function should fill
these next pointers so that they point to inorder successor.

Solution (Use Reverse Inorder Traversal)


Traverse the given tree in reverse inorder traversal and keep track of
previously visited node. When a node is being visited, assign a
previously visited node as next.

// Javascript program to populate inorder traversal of all nodes

// A binary tree node


class Node
{

constructor(x) {
this.data = x;

https://www.geeksforgeeks.org/populate-inorder-successor-for-all-nodes/?ref=lbp 1/3
3/30/25, 10:20 PM Populate Inorder Successor for all nodes | GeeksforGeeks
236
this.left = null;
this.right = null;
}
}

let root;
let next = null;

/* Set next of p and all descendants of p by traversing them in


reverse Inorder */
function populateNext(node)
{
// The first visited node will be the rightmost node
// next of the rightmost node will be NULL
if (node != null)
{
// First set the next pointer in right subtree
populateNext(node.right);

// Set the next as previously visited node in reverse Inorder


node.next = next;

// Change the prev for subsequent node


next = node;

// Finally, set the next pointer in left subtree


populateNext(node.left);
}
}

/* Driver program to test above functions*/

/* Constructed binary tree is


10
/ \
8 12
/
3 */
root = new Node(10)
root.left = new Node(8)
root.right = new Node(12)
root.left.left = new Node(3)

// Populates nextRight pointer


// in all nodes
p = populateNext(root)

// Let us see the populated values


ptr = root.left.left

https://www.geeksforgeeks.org/populate-inorder-successor-for-all-nodes/?ref=lbp 2/3
3/30/25, 10:20 PM Populate Inorder Successor for all nodes | GeeksforGeeks
237

while (ptr != null)


{
// -1 is printed if there is no successor
let print = ptr.next != null ? ptr.next.data : -1;
document.write("Next of " + ptr.data + " is: " + print+"<br>"
ptr = ptr.next;
}

// This code is contributed by unknown2108

Output

Next of 3 is 8
Next of 8 is 10
Next of 10 is 12
Next of 12 is -1

Time Complexity: O(n)


Auxiliary Space : O(1)

https://www.geeksforgeeks.org/populate-inorder-successor-for-all-nodes/?ref=lbp 3/3
3/30/25, 10:21 PM Minimum swap required to convert binary tree to binary search tree | GeeksforGeeks
238

Minimum swap required to convert binary tree to


binary search tree
Last Updated : 25 Nov, 2024

Given an array arr[] which represents a Complete Binary Tree i.e., if


index i is the parent, index 2*i + 1 is the left child and index 2*i + 2 is
the right child. The task is to find the minimum number of swaps
required to convert it into a Binary Search Tree.

Examples:

Input: arr[] = [5, 6, 7, 8, 9, 10, 11]


Output: 3
Explanation:
Binary tree of the given array:

Swap 1: Swap node 8 with node 5.


Swap 2: Swap node 9 with node 10.
Swap 3: Swap node 10 with node 7.

So, minimum 3 swaps are required to obtain the below binary


search tree:

https://www.geeksforgeeks.org/minimum-swap-required-convert-binary-tree-binary-search-tree/?ref=lbp 1/5
3/30/25, 10:21 PM Minimum swap required to convert binary tree to binary search tree | GeeksforGeeks
239

Input: arr[] = [1, 2, 3]


Output: 1
Explanation:
Binary tree of the given array:

After swapping node 1 with node 2, obtain the below binary


search tree:

https://www.geeksforgeeks.org/minimum-swap-required-convert-binary-tree-binary-search-tree/?ref=lbp 2/5
3/30/25, 10:21 PM Minimum swap required to convert binary tree to binary search tree | GeeksforGeeks
240

Approach:

The idea is to use the fact that inorder traversal of Binary


Search Tree is in increasing order of their value.
So, find the inorder traversal of the Binary Tree and store it in
the array and try to sort the array. The minimum number of
swap required to get the array sorted will be the answer.

C++ Java Python C# JavaScript

// Javascript program for Minimum swap required


// to convert binary tree to binary search tree

// Inorder traversal to get values in sorted order


function inorder(arr, inorderArr, index) {

// If index is out of bounds, return


if (index >= arr.length)
return;

// Recursively visit left subtree


inorder(arr, inorderArr, 2 * index + 1);

// Store current node value in array


inorderArr.push(arr[index]);

// Recursively visit right subtree


inorder(arr, inorderArr, 2 * index + 2);
}

// Function to calculate minimum swaps to sort inorder


// traversal
function minSwaps(arr) {

https://www.geeksforgeeks.org/minimum-swap-required-convert-binary-tree-binary-search-tree/?ref=lbp 3/5
3/30/25, 10:21 PM Minimum swap required to convert binary tree to binary search tree | GeeksforGeeks
241
let inorderArr = [];

// Get the inorder traversal of the binary tree


inorder(arr, inorderArr, 0);

// Create an array of pairs to store value and original


// index
let t = inorderArr.map((val, i) => [val, i]);
let ans = 0;

// Sort the pair array based on values to get BST order


t.sort((a, b) => a[0] - b[0]);

// Find minimum swaps by detecting cycles


let visited = Array(arr.length)
.fill(false);

for (let i = 0; i < t.length; i++) {

// If the element is already in the correct


// position, continue
if (visited[i] || t[i][1] === i)
continue;

// Otherwise, perform swaps until the element is in


// the right place
let cycleSize = 0;
let j = i;

while (!visited[j]) {
visited[j] = true;
j = t[j][1];
cycleSize++;
}

// If there is a cycle, we need (cycleSize - 1)


// swaps to sort the cycle
if (cycleSize > 1) {
ans += (cycleSize - 1);
}
}

// Return total number of swaps


return ans;
}

let arr = [ 5, 6, 7, 8, 9, 10, 11 ];


console.log(minSwaps(arr));

Output

Time Complexity: O(n*logn) where n is the number of elements in


array.
https://www.geeksforgeeks.org/minimum-swap-required-convert-binary-tree-binary-search-tree/?ref=lbp 4/5
3/30/25, 10:21 PM Minimum swap required to convert binary tree to binary search tree | GeeksforGeeks
242
Auxiliary Space: O(n) because it is using extra space for array

Exercise: Can we extend this to normal binary tree, i.e., a binary tree
represented using left and right pointers, and not necessarily
complete?

https://www.geeksforgeeks.org/minimum-swap-required-convert-binary-tree-binary-search-tree/?ref=lbp 5/5
3/30/25, 10:21 PM Convert Binary Tree to Doubly Linked List using inorder traversal | GeeksforGeeks
243

Convert Binary Tree to Doubly Linked List using


inorder traversal
Last Updated : 30 Sep, 2024

Given a Binary Tree (BT), the task is to convert it to a Doubly Linked


List (DLL) in place. The left and right pointers in nodes will be used
as previous and next pointers respectively in converted DLL. The
order of nodes in DLL must be the same as the order of the given
Binary Tree. The first node of Inorder traversal (leftmost node in BT)
must be the head node of the DLL.

Examples:

Input:

Output:

https://www.geeksforgeeks.org/convert-binary-tree-to-doubly-linked-list-using-inorder-traversal/?ref=lbp 1/7
3/30/25, 10:21 PM Convert Binary Tree to Doubly Linked List using inorder traversal | GeeksforGeeks
244
Explanation: The above binary tree is converted into doubly
linked list where left pointer of the binary tree node act as the
previous node and right pointer of the binary tree node act as the
next node.

Input:

Output:

Explanation: The above binary tree is converted into doubly


linked list where left pointer of the binary tree node act as the
previous node and right pointer of the binary tree node act as the
next node.

Table of Content
[Naive Approach] Using Recursion – O(n) Time and O(h) Space
[Expected Approach] Using Morris Traversal Algorithm – O(n) Time
and O(1) Space

https://www.geeksforgeeks.org/convert-binary-tree-to-doubly-linked-list-using-inorder-traversal/?ref=lbp 2/7
3/30/25, 10:21 PM Convert Binary Tree to Doubly Linked List using inorder traversal | GeeksforGeeks
245
[Naive Approach] Using Recursion – O(n) Time and O(h) Space

The idea is to recursively traverse the binary tree using inorder


traversal. At each node, if left subtree exists, find theinorder
predecessor, then process the left subtree and link the current
node and predecessor. If right subtree exists, then find
theinorder successor, process the right subtree and then link the
current node and successor node.

Below is the implementation of the above approach:

C++ C Java Python C# JavaScript

// JavaScript program for in-place


// conversion of Binary Tree to DLL
class Node {
constructor(new_value) {
this.data = new_value;
this.left = null;
this.right = null;
}
}

// Inorder traversal to link nodes


function inorder(root) {

// if left subtree exists


if (root.left) {

// find the inorder predecessor of root node


let pred = root.left;
while (pred.right) {
pred = pred.right;
}

// process the left subtree


inorder(root.left);

// link the predecessor and root node


pred.right = root;
root.left = pred;
}

// if right subtree exists


if (root.right) {

// find the inorder successor of root node


let succ = root.right;
while (succ.left) {
succ = succ.left;
}

https://www.geeksforgeeks.org/convert-binary-tree-to-doubly-linked-list-using-inorder-traversal/?ref=lbp 3/7
3/30/25, 10:21 PM Convert Binary Tree to Doubly Linked List using inorder traversal | GeeksforGeeks
246
// process the right subtree
inorder(root.right);

// link the successor and root node


root.right = succ;
succ.left = root;
}
}

// Function to convert binary tree to doubly linked list


function bToDLL(root) {

// return if root is null


if (root === null) return root;

// find the head of dll


let head = root;
while (head.left !== null)
head = head.left;

// recursively convert the tree into dll


inorder(root);

return head;
}

function printList(head) {
let curr = head;

while (curr !== null) {


console.log(curr.data);
curr = curr.right;
}
}

// Create a hard coded binary tree


// 10
// / \
// 12 15
// / \ /
// 25 30 36
let root = new Node(10);
root.left = new Node(12);
root.right = new Node(15);
root.left.left = new Node(25);
root.left.right = new Node(30);
root.right.left = new Node(36);

let head = bToDLL(root);

printList(head);

Output

25 12 30 10 36 15

https://www.geeksforgeeks.org/convert-binary-tree-to-doubly-linked-list-using-inorder-traversal/?ref=lbp 4/7
3/30/25, 10:21 PM Convert Binary Tree to Doubly Linked List using inorder traversal | GeeksforGeeks
247
Time Complexity: O(n), where n is the number of node in the tree.
Auxiliary Space: O(h), where h is the height of tree.

[Expected Approach] Using Morris Traversal Algorithm – O(n)


Time and O(1) Space

The idea is to use Morris traversal algorithmto traverse the


binary tree, while maintaining proper linkages between the
nodes.

Step by step implementation:

Initialize pointers head and tail. head will point to the head node of
the resultant dll and tail will point to the last node in dll.
Initialize another pointer curr, which will initially point to root node.
Start traversing until curr is not NULL
If curr.left is null, then add the current node to the list (If head is
empty, then make this node as head node) and move curr to
curr.right.
If curr.left is not null, then find the inorder predecessor of the
current node. Let that node be ‘pred’. There are two possibilites:
If pred.right is equal to null, then create a link between
pred and curr, by setting pred.right = curr and set curr =
curr.left.
If pred->right is equal to curr, then this means we have
traversed the left subtree and now we can add the curr
node to the list. Then set curr = curr->right.
Return the head.

C++ C Java Python C# JavaScript

// JavaScript program for in-place


// conversion of Binary Tree to DLL

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

https://www.geeksforgeeks.org/convert-binary-tree-to-doubly-linked-list-using-inorder-traversal/?ref=lbp 5/7
3/30/25, 10:21 PM Convert Binary Tree to Doubly Linked List using inorder traversal | GeeksforGeeks
248
}
}

function morrisTraversal(root) {

// return if root is null


if (root === null) return root;

// head and tail node for the dll


let head = null, tail = null;

let curr = root;

while (curr !== null) {

// if left tree does not exists,


// then add the curr node to the
// dll and set curr = curr.right
if (curr.left === null) {
if (head === null) {
head = tail = curr;
} else {
tail.right = curr;
curr.left = tail;
tail = curr;
}
curr = curr.right;
} else {
let pred = curr.left;

// find the inorder predecessor


while (pred.right !== null && pred.right !== curr) {
pred = pred.right;
}

// create a linkage between pred and curr


if (pred.right === null) {
pred.right = curr;
curr = curr.left;
}

// if pred.right = curr, it means


// we have processed the left subtree,
// and we can add curr node to list
else {
tail.right = curr;
curr.left = tail;
tail = curr;

curr = curr.right;
}
}
}

return head;
}

function printList(head) {
let curr = head;

https://www.geeksforgeeks.org/convert-binary-tree-to-doubly-linked-list-using-inorder-traversal/?ref=lbp 6/7
3/30/25, 10:21 PM Convert Binary Tree to Doubly Linked List using inorder traversal | GeeksforGeeks
249
while (curr !== null) {
console.log(curr.data);
curr = curr.right;
}
}

// Create a hard coded binary tree


// 10
// / \
// 12 15
// / \ /
// 25 30 36
let root = new Node(10);
root.left = new Node(12);
root.right = new Node(15);
root.left.left = new Node(25);
root.left.right = new Node(30);
root.right.left = new Node(36);

let head = morrisTraversal(root);

printList(head);

Output

25 12 30 10 36 15

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


Auxiliary Space: O(1)

https://www.geeksforgeeks.org/convert-binary-tree-to-doubly-linked-list-using-inorder-traversal/?ref=lbp 7/7
3/30/25, 10:22 PM Convert a tree to forest of even nodes | GeeksforGeeks
250

Convert a tree to forest of even nodes


Last Updated : 25 Nov, 2024

Given a tree of n even nodes. The task is to find the maximum number
of edges to be removed from the given tree to obtain a forest of trees
having an even number of nodes. This problem is always solvable as
the given graph has even nodes.

Examples:

Input:

Output: 2
Explanation: By removing 2 edges shown below, we can obtain
the forest with even node tree.

https://www.geeksforgeeks.org/convert-tree-forest-even-nodes/?ref=lbp 1/4
3/30/25, 10:22 PM Convert a tree to forest of even nodes | GeeksforGeeks
251

Approach:

The idea is to find a subtree with even number of nodes and


remove it from rest of tree by removing the edge connecting it.
After removal, we are left with tree with even node only
because initially we have even number of nodes in the tree and
removed subtree has also even node. Repeat the same
procedure until we left with the tree that cannot be further
decomposed in this manner.

To do this, the idea is to use Depth First Search to traverse the


tree. Implement DFS function in such a manner that it will return
number of nodes in the subtree whose root is node on which
DFS is performed. If the number of nodes is even then remove
the edge, else ignore.

C++ Java Python C# JavaScript

// JavaScript program to find maximum number to be removed


// to convert a tree into a forest containing trees of
// even number of nodes

function dfs(tree, visit, ans, node) {


let num = 0;

// Mark node as visited.


visit[node] = true;

// Traverse the adjacency list to find non-visited node.


for (let neighbor of tree[node]) {
if (!visit[neighbor]) {

https://www.geeksforgeeks.org/convert-tree-forest-even-nodes/?ref=lbp 2/4
3/30/25, 10:22 PM Convert a tree to forest of even nodes | GeeksforGeeks
252
// Finding number of nodes of the subtree.
let cnt = dfs(tree, visit, ans, neighbor);

// If nodes are even, increment number


// of edges to remove.
if (cnt % 2 === 0) {
ans.count++;
} else {

// Else leave the node as child of subtree.


num += cnt;
}
}
}

return num + 1;
}

// Return the maximum number of edges to remove


// to make forest.
function maxEdge(tree, n) {
const visit = new Array(n + 1).fill(false);
const ans = { count: 0 };

// Perform DFS from node 1


dfs(tree, visit, ans, 1);

return ans.count;
}

const n = 10;

// Tree structure:
//
// 1
// / | \
// 2 3 4
// / \ | |
// 5 6 7 8
// / \
// 9 10
const tree = Array.from({ length: n + 1 }, () => []);

tree[1].push(2);
tree[2].push(1);
tree[1].push(3);
tree[3].push(1);
tree[1].push(4);
tree[4].push(1);
tree[2].push(5);
tree[5].push(2);
tree[2].push(6);
tree[6].push(2);
tree[3].push(7);
tree[7].push(3);
tree[4].push(8);
tree[8].push(4);
tree[8].push(9);

https://www.geeksforgeeks.org/convert-tree-forest-even-nodes/?ref=lbp 3/4
3/30/25, 10:22 PM Convert a tree to forest of even nodes | GeeksforGeeks
253
tree[9].push(8);
tree[8].push(10);
tree[10].push(8);

console.log(maxEdge(tree, n));

Output

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


Auxiliary Space: O(n) For taking visiting array.

https://www.geeksforgeeks.org/convert-tree-forest-even-nodes/?ref=lbp 4/4
3/30/25, 10:22 PM Flip Binary Tree | GeeksforGeeks
254

Flip Binary Tree


Last Updated : 23 Oct, 2024

Given a binary tree, the task is to flip the binary tree towards the right
direction that is clockwise.

Input:

Output:

https://www.geeksforgeeks.org/flip-binary-tree/?ref=lbp 1/6
3/30/25, 10:22 PM Flip Binary Tree | GeeksforGeeks
255

Explanation: In the flip operation, the leftmost node becomes


the root of the flipped tree and its parent becomes its right child
and the right sibling becomes its left child and the same should
be done for all leftmost nodes recursively.

Table of Content
[Expected Approach – 1] Using Recursion – O(n) Time and O(n)
Space
[Expected Approach – 2] Iterative Approach – O(n) Time and O(1)
Space

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


Space

The idea is to recursively flip the binary tree by swapping the


left and right subtrees of each node. After flipping, the tree’s
structure will be reversed, and the new root of the flipped tree
will be the original leftmost leaf node.

Below is the main rotation code of a subtree:

root->left->left = root->right
root->left->right = root
root->left = NULL
root->right = NULL

Below is the implementation of the above approach:

C++ Java Python C# JavaScript


https://www.geeksforgeeks.org/flip-binary-tree/?ref=lbp 2/6
3/30/25, 10:22 PM Flip Binary Tree | GeeksforGeeks
256
// JavaScript program to flip a binary
// tree using recursion

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

// Method to flip the binary tree


function flipBinaryTree(root) {

if (root === null) return root;


if (root.left === null && root.right === null) return root;

// Recursively call the same method


const flippedRoot = flipBinaryTree(root.left);

// Rearranging main root Node after returning


// from recursive call
root.left.left = root.right;
root.left.right = root;
root.left = root.right = null;

return flippedRoot;
}

// Iterative method to do level order traversal


// line by line
function printLevelOrder(root) {

if (root === null) return;

// Create an empty queue for level


// order traversal
const queue = [root];

while (queue.length > 0) {


let nodeCount = queue.length;

while (nodeCount > 0) {


const node = queue.shift();
console.log(node.data + " ");
if (node.left !== null) queue.push(node.left);
if (node.right !== null) queue.push(node.right);
nodeCount--;
}
console.log();
}
}

// Make a binary tree


//
// 1
// / \
// 2 3

https://www.geeksforgeeks.org/flip-binary-tree/?ref=lbp 3/6
3/30/25, 10:22 PM Flip Binary Tree | GeeksforGeeks
257
// / \
// 4 5
const root = new Node(1);
root.left = new Node(2);
root.right = new Node(3);
root.right.left = new Node(4);
root.right.right = new Node(5);

const flippedRoot = flipBinaryTree(root);


printLevelOrder(flippedRoot);

Output

2
3 1
4 5

[Expected Approach – 2] Iterative Approach – O(n) Time and


O(n) Space

The iterative solution follows the same approach as the


recursive one, the only thing we need to pay attention to is
saving the node information that will be overwritten.

Below is the implementation of the above approach:

C++ Java Python C# JavaScript

// JavaScript program to flip a binary


// tree using iterative approach

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

function flipBinaryTree(root) {

// Initializing the pointers to do the


// swapping and storing states
let curr = root;
let next = null;
let prev = null;
let ptr = null;

https://www.geeksforgeeks.org/flip-binary-tree/?ref=lbp 4/6
3/30/25, 10:22 PM Flip Binary Tree | GeeksforGeeks
258
while (curr !== null) {

// Pointing the next pointer to the


// current next of left
next = curr.left;

// Making the right child of prev


// as curr left child
curr.left = ptr;

// Storing the right child of


// curr in ptr
ptr = curr.right;

curr.right = prev;
prev = curr;
curr = next;
}

return prev;
}

// Iterative method to do level order


// traversal line by line
function printLevelOrder(root) {

if (root === null) return;

// Create an empty queue for


// level order traversal
const queue = [root];

while (queue.length > 0) {


let nodeCount = queue.length;

while (nodeCount > 0) {


const node = queue.shift();
console.log(node.data + " ");
if (node.left !== null) queue.push(node.left);
if (node.right !== null) queue.push(node.right);
nodeCount--;
}
console.log();
}
}

// Make a binary tree


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

https://www.geeksforgeeks.org/flip-binary-tree/?ref=lbp 5/6
3/30/25, 10:22 PM Flip Binary Tree | GeeksforGeeks
259
const flippedRoot = flipBinaryTree(root);
printLevelOrder(flippedRoot);

Output

2
3 1
4 5

https://www.geeksforgeeks.org/flip-binary-tree/?ref=lbp 6/6
3/30/25, 10:22 PM Print root to leaf paths without using recursion | GeeksforGeeks
260

Print root to leaf paths without using recursion


Last Updated : 07 Oct, 2024

Given a Binary Tree of nodes, the task is to find all the possible paths
from the root node to all the leaf nodes of the binary tree.

Example:

Input:

Output:
124
125
13

Table of Content
[Expected Approach – 1] Using Parent HashMap – O(n) Time and
O(n) Space
[Expected Approach – 2] Using Stack – O(n) Time and O(n) Space

[Expected Approach – 1] Using Parent HashMap – O(n) Time


and O(n) Space
https://www.geeksforgeeks.org/print-root-leaf-path-without-using-recursion/?ref=lbp 1/6
3/30/25, 10:22 PM Print root to leaf paths without using recursion | GeeksforGeeks
261
The idea is to use a preorder traversal technique using a stack,
and maintain hashmap to keep track of each node’s parent,
When we reach at leaf node, print path from root to that lead
node using parent map.

Follow the steps below to solve the problem:

Push the root node onto the stack and Store the root’s parent as
null in the parent map.
While the stack is not empty, pop the top node
If the node is a leaf node then Trace the path from the leaf
node to the root using the parent map and print the path.
If the node has a right child, push it onto the stack and
store its parent in the map.
If the node has a left child, push it onto the stack and store
its parent in the map.

Below is the implementation of this idea.

C++ Java Python C# JavaScript

// Javascript program to Print root to leaf path without


// using recursion

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

// Function to print root to leaf path for a leaf


// using parent nodes stored in map
function printTopToBottomPath(curr, parent) {
let stk = [];

// start from leaf node and keep on pushing


// nodes into stack till root node is reached
while (curr) {
stk.push(curr);
curr = parent.get(curr);
}

// Start popping nodes from stack and print them


while (stk.length > 0) {

https://www.geeksforgeeks.org/print-root-leaf-path-without-using-recursion/?ref=lbp 2/6
3/30/25, 10:22 PM Print root to leaf paths without using recursion | GeeksforGeeks
262
curr = stk.pop();
process.stdout.write(curr.data + " ");
}
console.log();
}

// An iterative function to do preorder traversal


// of binary tree and print root to leaf path
// without using recursion
function printRootToLeaf(root) {

if (root === null) return;

// Create an empty stack and push root to it


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

// Create a map to store parent pointers of binary


// tree nodes
let parent = new Map();

// parent of root is NULL


parent.set(root, null);

while (nodeStack.length > 0) {

// Pop the top item from stack


let current = nodeStack.pop();

// If leaf node encountered, print Top To


// Bottom path
if (!current.left && !current.right) {
printTopToBottomPath(current, parent);
}

// Push right & left children of the popped node


// to stack. Also set their parent pointer in
// the map
// Note that right child is pushed first so that
// left is processed first
if (current.right) {
parent.set(current.right, current);
nodeStack.push(current.right);
}
if (current.left) {
parent.set(current.left, current);
nodeStack.push(current.left);
}
}
}

// Constructed binary tree is


// 10
// / \
// 8 2
// / \ /
// 3 5 2
let root = new Node(10);
root.left = new Node(8);

https://www.geeksforgeeks.org/print-root-leaf-path-without-using-recursion/?ref=lbp 3/6
3/30/25, 10:22 PM Print root to leaf paths without using recursion | GeeksforGeeks
263
root.right = new Node(2);
root.left.left = new Node(3);
root.left.right = new Node(5);
root.right.left = new Node(2);

printRootToLeaf(root);

Output

10 8 3
10 8 5
10 2 2

Note : We can optimize this approach. We do not need to maintain


parent map. Below there is another approach by we can print all path
from root to leaf without using parent array.

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


Space

The idea is to use stack to store pairs of nodes and their


respective paths from the root, starting with the root node and
its value, traverse iteratively by processing each node by
popping it from the stack. if the node is a leaf, its path is added
to the result. else if the node has children, the right and left
children are pushed onto the stack along with their updated
paths.

Follow the steps below to solve the problem:

Initialize stack, that stores pairs of nodes and the path from the
root to that node.
Push the root node and its path (starting with just the root’s value)
onto the stack.
While the stack isn’t empty, pop a pair of node and its path from
the stack.
If the current node is a leaf, add its path to the result.
If the current node has a right child, push the right child
and its updated path onto the stack.

https://www.geeksforgeeks.org/print-root-leaf-path-without-using-recursion/?ref=lbp 4/6
3/30/25, 10:22 PM Print root to leaf paths without using recursion | GeeksforGeeks
264
If the current node has a left child, push the left child and
its updated path onto the stack.
return result which represents all the paths from root-to-leaf.

Below is the implementation of the above approach:

C++ Java Python C# JavaScript

// JavaScript code to print all paths from


// root node to leaf node using stack.

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

// Function to get all paths from root


// to leaf nodes using a stack
function Paths(root) {
const result = [];
if (!root) return result;

// Stack to store pairs of nodes and the


// path from the root to that node
const stk = [[root, [root.data]]];

while (stk.length > 0) {

// Get the current node and its


// associated path from the stack
const [currNode, path] = stk.pop();

// If the current node is a leaf node,


// add its path to the result
if (!currNode.left && !currNode.right) {
result.push(path);
}

// If the current node has a right child,


// push it to the stack with its path
if (currNode.right) {
const rightPath = [...path, currNode.right.data];
stk.push([currNode.right, rightPath]);
}

// If the current node has a left child,


// push it to the stack with its path
if (currNode.left) {
const leftPath = [...path, currNode.left.data];
stk.push([currNode.left, leftPath]);
}
}

https://www.geeksforgeeks.org/print-root-leaf-path-without-using-recursion/?ref=lbp 5/6
3/30/25, 10:22 PM Print root to leaf paths without using recursion | GeeksforGeeks
265
return result;
}

// Constructed binary tree is


// 10
// / \
// 8 2
// / \ /
// 3 5 2
const 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);

const allPaths = Paths(root);

allPaths.forEach(path => {
console.log(path.join(' '));
});

Output

10 8 3
10 8 5
10 2 2

Related article:

Print root to leaf paths using recursion

https://www.geeksforgeeks.org/print-root-leaf-path-without-using-recursion/?ref=lbp 6/6
3/30/25, 10:22 PM Check if given Preorder, Inorder and Postorder traversals are of same tree | GeeksforGeeks
266

Check if given Preorder, Inorder and Postorder


traversals are of same tree
Last Updated : 30 Oct, 2024

Given the Preorder, Inorder, and Postorder traversals of some trees,


the task is to check if they all belong to the same tree.

Examples:

Input: inOrder[] = [4, 2, 5, 1, 3]


preOrder[] = [1, 2, 4, 5, 3]
postOrder = [4, 5, 2, 3, 1]

Output: True
Explanation: All of the above three traversals are of the same
tree:

Input: inOrder = [4, 2, 5, 1, 3]


preOrder = [1, 5, 4, 2, 3]
postOrder = [4, 1, 2, 3, 5]

https://www.geeksforgeeks.org/check-if-given-preorder-inorder-and-postorder-traversals-are-of-same-tree/?ref=lbp 1/7
3/30/25, 10:22 PM Check if given Preorder, Inorder and Postorder traversals are of same tree | GeeksforGeeks
267
Output: False

Table of Content
[Naive Approach] Constructing the Tree – O(n^2) Time and O(n)
Space
[Expected Approach] Using Hashing – O(n) Time and O(n) Space

[Naive Approach] Constructing the Tree – O(n^2) Time and


O(n) Space

The idea is to solve this problem will be to first construct a tree


using two of the three given traversals and then do the third
traversal on this constructed tree and compare it with the given
traversal. Here, we use Inorder and Preorder traversals to
construct the tree. We may also use Inorder and Postorder
traversal instead of Preorder traversal for tree construction. You
may refer to this post on how to construct a tree from given
Inorder and Preorder traversal. After constructing the tree, we
will obtain the Postorder traversal of this tree and compare it
with the given Postorder traversal.

Below is the implementation of the above approach:

C++ Java Python C# JavaScript

// Javascript program to check if all three traversals


// are of the same tree using List
class Node {
constructor(x) {
this.data = x;
this.left = null;
this.right = null;
}
}

// Utility function to find the index of


// value in inOrder
function search(inOrder, start, end, value) {

// Traverse to find the index of


// 'value' in the inOrder traversal
for (let i = start; i <= end; i++) {
if (inOrder[i] === value) {
return i;

https://www.geeksforgeeks.org/check-if-given-preorder-inorder-and-postorder-traversals-are-of-same-tree/?ref=lbp 2/7
3/30/25, 10:22 PM Check if given Preorder, Inorder and Postorder traversals are of same tree | GeeksforGeeks
268
}
}
return -1;
}

// Recursive function to construct binary


// tree from Inorder and Preorder
function buildTree(inOrder, preOrder,
preIndex, inStart, inEnd) {

// Base case: If start index exceeds


// end index
if (inStart > inEnd) {
return null;
}

// Create a new node with current


// preOrder element
let root = new Node(preOrder[preIndex[0]]);
preIndex[0]++;

// If no children, return current node


if (inStart === inEnd) {
return root;
}

// Find index of this node in Inorder


// traversal
let inIndex = search(inOrder, inStart, inEnd, root.data);

// Recursively build the left subtree


root.left = buildTree(inOrder,
preOrder, preIndex, inStart, inIndex - 1);

// Recursively build the right subtree


root.right = buildTree(inOrder,
preOrder, preIndex, inIndex + 1, inEnd);

return root;
}

// Function to compare postorder traversal


// on constructed tree and given Postorder
function checkPostorder(root, postOrder, index) {

// If current node is null, return index


if (root === null) {
return index;
}

// Traverse the left subtree


index = checkPostorder(root.left,
postOrder, index);

// Traverse the right subtree


index = checkPostorder(root.right,
postOrder, index);

// Check if current node matches the

https://www.geeksforgeeks.org/check-if-given-preorder-inorder-and-postorder-traversals-are-of-same-tree/?ref=lbp 3/7
3/30/25, 10:22 PM Check if given Preorder, Inorder and Postorder traversals are of same tree | GeeksforGeeks
269
// postOrder element
if (root.data === postOrder[index]) {
index++;
}
else {
return -1;
}

return index;
}

let inOrder = [4, 2, 5, 1, 3];


let preOrder = [1, 2, 4, 5, 3];
let postOrder = [4, 5, 2, 3, 1];
let len = inOrder.length;
let preIndex = [0];

let root = buildTree(inOrder, preOrder,


preIndex, 0, len - 1);

let index = checkPostorder(root, postOrder, 0);

if (index === len) {


console.log("True");
} else {
console.log("False");
}

Output

True

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


Space

While building the tree from Inorder and Preorder traversal we


need to check if the inorder and preorder traversals are valid
themself for some tree, and if yes , then keep building the tree,
but if valid binary tree can not be built from given inorder and
preorder traversal, then we must stop building the tree and
return false. And also we can build the tree from inorder and
preorder traversal in O(n) time using hashmap to store the
indices of the inorder element’s array.

Below is the implementation of the above approach:

C++ Java Python C# JavaScript

https://www.geeksforgeeks.org/check-if-given-preorder-inorder-and-postorder-traversals-are-of-same-tree/?ref=lbp 4/7
3/30/25, 10:22 PM Check if given Preorder, Inorder and Postorder traversals are of same tree | GeeksforGeeks
270
// JavaScript implementation to validate tree
// traversals using hashing
function Node(newdata) {
this.data = newdata;
this.left = null;
this.right = null;
}

// Function to build tree from inorder and preorder


function buildTreeFromInorderPreorder(inStart, inEnd,
preIndex, preorder,
inorderIndexMap, notPossible) {

// Base case: if start index exceeds


// end index
if (inStart > inEnd) {
return null;
}

// Create the current root node


const rootData = preorder[preIndex[0]];
const root = new Node(rootData);
preIndex[0]++;

// Check if root data is in inorder index map


if (!(rootData in inorderIndexMap)) {
notPossible[0] = true;
return root;
}

// Find the index of root in inorder traversal


const inorderIndex = inorderIndexMap[rootData];

// Check if the index is valid


if (!(inStart <= inorderIndex && inorderIndex <= inEnd)) {
notPossible[0] = true;
return root;
}

// Recursively build the left subtree


root.left = buildTreeFromInorderPreorder(
inStart, inorderIndex - 1, preIndex,
preorder, inorderIndexMap, notPossible);

// Return if subtree construction is not possible


if (notPossible[0]) {
return root;
}

// Recursively build the right subtree


root.right = buildTreeFromInorderPreorder(
inorderIndex + 1, inEnd, preIndex, preorder,
inorderIndexMap, notPossible);

return root;
}

// Function to check if postorder traversal is correct


function checkPostorderCorrect(root, postIndex,
https://www.geeksforgeeks.org/check-if-given-preorder-inorder-and-postorder-traversals-are-of-same-tree/?ref=lbp 5/7
3/30/25, 10:22 PM Check if given Preorder, Inorder and Postorder traversals are of same tree | GeeksforGeeks
271
postorder) {

// Base case: if current node is null


if (root === null) {
return true;
}

// Check left subtree


if (!checkPostorderCorrect(root.left,
postIndex, postorder)) {
return false;
}

// Check right subtree


if (!checkPostorderCorrect(root.right,
postIndex, postorder)) {
return false;
}

// Compare current node with postorder element


if (root.data !== postorder[postIndex[0]]) {
return false;
}

postIndex[0]++;
return true;
}

// Main function to check all three traversals


function checkTree(preorder, inorder,
postorder, N) {

// Return true if tree is empty


if (N === 0) {
return true;
}

// Create a map for inorder indices


const inorderIndexMap = {};
for (let idx = 0; idx < inorder.length; idx++) {
inorderIndexMap[inorder[idx]] = idx;
}

const preIndex = [0];


const notPossible = [false];

// Build tree from inorder and preorder


const root = buildTreeFromInorderPreorder(
0, N - 1, preIndex, preorder, inorderIndexMap,
notPossible);

// Check if tree construction was possible


if (notPossible[0]) {
return false;
}

const postIndex = [0];

// Verify postorder traversal

https://www.geeksforgeeks.org/check-if-given-preorder-inorder-and-postorder-traversals-are-of-same-tree/?ref=lbp 6/7
3/30/25, 10:22 PM Check if given Preorder, Inorder and Postorder traversals are of same tree | GeeksforGeeks
272
return checkPostorderCorrect
(root, postIndex, postorder);
}

const inorder = [4, 2, 5, 1, 3];


const preorder = [1, 2, 4, 5, 3];
const postorder = [4, 5, 2, 3, 1];

const N = preorder.length;

if (checkTree(preorder, inorder, postorder, N)) {


console.log("True");
}
else {
console.log("False");
}

Output

True

https://www.geeksforgeeks.org/check-if-given-preorder-inorder-and-postorder-traversals-are-of-same-tree/?ref=lbp 7/7
3/30/25, 10:23 PM Check whether a given Binary Tree is Complete or not (Iterative Solution) | GeeksforGeeks
273

Check whether a given Binary Tree is Complete or


not (Iterative Solution)
Last Updated : 30 Oct, 2024

Given a Binary Tree, the task is to check whether the given Binary Tree
is a Complete Binary Tree or not.
A complete binary tree is a binary tree in which every level, except
possibly the last, is completely filled, and all nodes are as far left as
possible.

Examples:

The following trees are examples of Complete Binary Trees:

The following trees are examples of Non-Complete Binary Trees:

https://www.geeksforgeeks.org/check-if-a-given-binary-tree-is-complete-tree-or-not/?ref=lbp 1/6
3/30/25, 10:23 PM Check whether a given Binary Tree is Complete or not (Iterative Solution) | GeeksforGeeks
274

Table of Content
[Expected Approach – 1] Using Level-Order Traversal – O(n) Time
and O(n) Space
[Expected Approach – 2] Checking position of NULL – O(n) Time
and O(n) Space

[Expected Approach – 1] Using Level-Order Traversal – O(n)


Time and O(n) Space

The idea is to do a level order traversal starting from the root. In


the traversal, once a node is found which is Not a Full Node, all
the following nodes must be leaf nodes. A node is ‘Full Node’ if
both left and right children are not empty (or not NULL).

Also, one more thing needs to be checked to handle the below case: If
a node has an empty left child, then the right child must be empty.

https://www.geeksforgeeks.org/check-if-a-given-binary-tree-is-complete-tree-or-not/?ref=lbp 2/6
3/30/25, 10:23 PM Check whether a given Binary Tree is Complete or not (Iterative Solution) | GeeksforGeeks
275

Below is the implementation of the above approach:

C++ Java Python C# JavaScript

// JavaScript implementation to check if a


// Binary Tree is complete
class Node {
constructor(x) {
this.data = x;
this.left = null;
this.right = null;
}
}

// Function to check if the binary


// tree is complete
function isCompleteBinaryTree(root) {
if (root === null)
return true;

const q = [];
q.push(root);
let end = false;

while (q.length > 0) {


const current = q.shift();

// Check left child


if (current.left) {
if (end)
return false;
q.push(current.left);
}
else {

// If left child is missing,


// mark the end
end = true;

https://www.geeksforgeeks.org/check-if-a-given-binary-tree-is-complete-tree-or-not/?ref=lbp 3/6
3/30/25, 10:23 PM Check whether a given Binary Tree is Complete or not (Iterative Solution) | GeeksforGeeks
276
}

// Check right child


if (current.right) {
if (end)
return false;
q.push(current.right);
}
else {

// If right child is missing,


// mark the end
end = true;
}
}

return true;
}

// Representation of Input tree


// 1
// / \
// 2 3
// / \ /
// 4 5 6
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);

if (isCompleteBinaryTree(root))
console.log("True");
else
console.log("False");

Output

True

[Expected Approach – 2] Checking position of NULL – O(n)


Time and O(n) Space

A simple idea would be to check whether the NULL Node


encountered is the last node of the Binary Tree. If the null node
encountered in the binary tree is the last node then it is a
complete binary tree and if there exists a valid node even after
encountering a null node then the tree is not a complete binary
tree.

https://www.geeksforgeeks.org/check-if-a-given-binary-tree-is-complete-tree-or-not/?ref=lbp 4/6
3/30/25, 10:23 PM Check whether a given Binary Tree is Complete or not (Iterative Solution) | GeeksforGeeks
277
Below is the implementation of the above approach:

C++ Java Python C# JavaScript

// JavaScript implementation to check if a binary


// tree is complete by position of null
class Node {
constructor(x) {
this.data = x;
this.left = null;
this.right = null;
}
}

// Function to check if the binary


// tree is complete
function isCompleteBinaryTree(root) {
if (root === null) {
return true;
}

const queue = [];


queue.push(root);
let nullEncountered = false;

while (queue.length > 0) {


const curr = queue.shift();

if (curr === null) {

// If we have seen a null node,


// set the flag
nullEncountered = true;
}
else {

// If that null node is not the last


// node, return false
if (nullEncountered) {
return false;
}

// Push both nodes even if


// there are null
queue.push(curr.left);
queue.push(curr.right);
}
}

return true;
}

// Representation of Input tree


// 1
// / \
// 2 3
// / \ /
// 4 5 6
https://www.geeksforgeeks.org/check-if-a-given-binary-tree-is-complete-tree-or-not/?ref=lbp 5/6
3/30/25, 10:23 PM Check whether a given Binary Tree is Complete or not (Iterative Solution) | GeeksforGeeks
278
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);

if (isCompleteBinaryTree(root)) {
console.log("True");
}
else {
console.log("False");
}

Output

True

https://www.geeksforgeeks.org/check-if-a-given-binary-tree-is-complete-tree-or-not/?ref=lbp 6/6
3/30/25, 10:23 PM Check if a binary tree is subtree of another binary tree | Set 2 | GeeksforGeeks
279

Check if a binary tree is subtree of another binary


tree | Set 2
Last Updated : 11 Oct, 2023

Given two binary trees, check if the first tree is a subtree of the second
one. A subtree of a tree T is a tree S consisting of a node in T and all of
its descendants in T.
The subtree corresponding to the root node is the entire tree; the
subtree corresponding to any other node is called a proper subtree.
For example, in the following case, Tree1 is a subtree of Tree2.

Tree1
x
/ \
a b
\
c
Tree2
z
/ \
x e
/ \ \
a b k
\
c

We have discussed an O(n2) solution for this problem. In this post, the
O(n) solution is discussed. The idea is based on the fact that inorder
and preorder/postorder uniquely identify a binary tree. Tree S is a
subtree of T if both inorder and preorder traversals of S are substrings
of inorder and preorder traversals of T respectively.
Following are detailed steps.
https://www.geeksforgeeks.org/check-binary-tree-subtree-another-binary-tree-set-2/?ref=lbp 1/10
3/30/25, 10:23 PM Check if a binary tree is subtree of another binary tree | Set 2 | GeeksforGeeks
280
1) Find inorder and preorder traversals of T, and store them in two
auxiliary arrays inT[] and preT[].
2) Find inorder and preorder traversals of S, and store them in two
auxiliary arrays inS[] and preS[].
3) If inS[] is a subarray of inT[] and preS[] is a subarray preT[], then S
is a subtree of T. Else not.
We can also use postorder traversal in place of preorder in the above
algorithm.
Let us consider the above example

Inorder and Preorder traversals of the big tree are.


inT[] = {a, c, x, b, z, e, k}
preT[] = {z, x, a, c, b, e, k}
Inorder and Preorder traversals of small tree are
inS[] = {a, c, x, b}
preS[] = {x, a, c, b}
We can easily figure out that inS[] is a subarray of
inT[] and preS[] is a subarray of preT[].

EDIT

The above algorithm doesn't work for cases where a tree is


present
in another tree, but not as a subtree. Consider the following
example.
Tree1
x
/ \
a b
/
c
Tree2
x
/ \
a b
/ \
c d
Inorder and Preorder traversals of the big tree or Tree2 are.
inT[] = {c, a, x, b, d}

https://www.geeksforgeeks.org/check-binary-tree-subtree-another-binary-tree-set-2/?ref=lbp 2/10
3/30/25, 10:23 PM Check if a binary tree is subtree of another binary tree | Set 2 | GeeksforGeeks
281
preT[] = {x, a, c, b, d}
Inorder and Preorder traversals of small tree or Tree1 are-
inS[] = {c, a, x, b}
preS[] = {x, a, c, b}
The Tree2 is not a subtree of Tree1, but inS[] and preS[] are
subarrays of inT[] and preT[] respectively.

The above algorithm can be extended to handle such cases by adding


a special character whenever we encounter NULL in inorder and
preorder traversals. Thanks to Shivam Goel for suggesting this
extension.
Following is the implementation of the above algorithm.

const MAX = 100

// class for a tree node


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

// A utility function to create a new BST node


function newNode(item){
temp = new Node()
temp.key = item
return temp
}

// A utility function to store inorder traversal of tree rooted


// with root in an array arr[]. Note that i is passed as reference
function storeInorder(root, i){
if (root == null)
return '$'
res = storeInorder(root.left, i)
res += root.key
res += storeInorder(root.right, i)
return res
}

// A utility function to store preorder traversal of tree rooted


https://www.geeksforgeeks.org/check-binary-tree-subtree-another-binary-tree-set-2/?ref=lbp 3/10
3/30/25, 10:23 PM Check if a binary tree is subtree of another binary tree | Set 2 | GeeksforGeeks
282
// with root in an array arr[]. Note that i is passed as reference
function storePreOrder(root, i){
if (root == null)
return '$'
res = root.key
res += storePreOrder(root.left, i)
res += storePreOrder(root.right, i)
return res
}

// This function returns true if S is a subtree of T, otherwise false


function isSubtree(T, S){
// base cases
if (S == null)
return true
if (T == null)
return false

// Store Inorder traversals of T and S in inT[0..m-1]


// and inS[0..n-1] respectively
let m = 0
let n = 0
let inT = storeInorder(T, m)
let inS = storeInorder(S, n)

// If inS[] is not a substring of inT[], return false


res = true
if(inT.indexOf(inT) !== -1)
res = true
else
res = false
if(res == false)
return res

// Store Preorder traversals of T and S in preT[0..m-1]


// and preS[0..n-1] respectively
m = 0
n = 0
let preT = storePreOrder(T, m)
let preS = storePreOrder(S, n)

// If preS[] is not a substring of preT[], return false


// Else return true
if(preT.indexOf(preS) !== -1)
return true
else
return false
}

https://www.geeksforgeeks.org/check-binary-tree-subtree-another-binary-tree-set-2/?ref=lbp 4/10
3/30/25, 10:23 PM Check if a binary tree is subtree of another binary tree | Set 2 | GeeksforGeeks
283
// Driver program to test above function

let T = new newNode('a')


T.left = new newNode('b')
T.right = new newNode('d')
T.left.left = new newNode('c')
T.right.right = new newNode('e')

let S = new newNode('a')


S.left = new newNode('b')
S.left.left = new newNode('c')
S.right = new newNode('d')

if (isSubtree(T, S))
document.write("Yes: S is a subtree of T","</br>")
else
document.write("No: S is NOT a subtree of T","</br>")

// This code is contributed by shinjanpatra

Output

No: S is NOT a subtree of T

Time Complexity: Inorder and Preorder traversals of Binary Tree take


O(n) time. The function strstr() can also be implemented in O(n) time
using the KMP string matching algorithm.
Auxiliary Space: O(n)

EASY: String Serialisation Method & using KMP


algorithm:-

The method is pretty similar to the String-Matching algorithms


here the approach is to store the preorder of root and sub root
into two strings and then find the str_subtroot in str_root if it is
present return true otherwise false.

https://www.geeksforgeeks.org/check-binary-tree-subtree-another-binary-tree-set-2/?ref=lbp 5/10
3/30/25, 10:23 PM Check if a binary tree is subtree of another binary tree | Set 2 | GeeksforGeeks
284
Below I am attaching the whole program to perform the above
implementation I hope it is easy to understand

Algorithm :

1. Store the inorder traversal of root in tree1

2. Similarly store the inorder traversal of subRoot in tree2

3. Search tree2 in tree1 if its present return true otherwise false

Note : You can use any other string matching algorithm such as
KMP algorithm, Boyer Moore Searching, Trie | (Insert and Search)

class TreeNode {
constructor(val) {
this.val = val;
this.left = null;
this.right = null;
}
}

class Solution {
isSubtree(root, subRoot) {
const tree1 = [];
const tree2 = [];
this.convertPreorder(root, tree1);
this.convertPreorder(subRoot, tree2);

const tree1String = tree1.join(",");


const tree2String = tree2.join(",");

if (tree1String.indexOf(tree2String) === -1)


return false;

return true;
}

convertPreorder(root, arr) {
if (root === null) {
arr.push("#");
} else {
arr.push(root.val);
this.convertPreorder(root.left, arr);
this.convertPreorder(root.right, arr);
https://www.geeksforgeeks.org/check-binary-tree-subtree-another-binary-tree-set-2/?ref=lbp 6/10
3/30/25, 10:23 PM Check if a binary tree is subtree of another binary tree | Set 2 | GeeksforGeeks
285
}
}

inOrderTraversal(root) {
if (root === null)
return;

this.inOrderTraversal(root.left);
console.log(root.val + " ");
this.inOrderTraversal(root.right);
}
}

/*Creating the root tree*/


const root = new TreeNode(3);
root.left = new TreeNode(4);
root.right = new TreeNode(5);
root.left.left = new TreeNode(1);
root.left.right = new TreeNode(2);

/*Creating the subroot tree */


const subRoot = new TreeNode(4);
subRoot.left = new TreeNode(1);
subRoot.right = new TreeNode(2);

// creating one instance of obj


const myObj = new Solution();

console.log("Our Tree1 and Tree2 Looks like:\n");


console.log("\nTree1: ");
myObj.inOrderTraversal(root);
console.log("\nTree2: ");
myObj.inOrderTraversal(subRoot);

// Calling the isSubtree function


if (myObj.isSubtree(root, subRoot))
console.log("\nYes Tree2 is subroot of Tree1\n");
else
console.log("\nNo Tree2 is not Subtree of Tree1\n");
// This Code is Contributed by Veerendra_Singh_Rajpoot

Output

Our Tree1 and Tree2 Looks like:

https://www.geeksforgeeks.org/check-binary-tree-subtree-another-binary-tree-set-2/?ref=lbp 7/10
3/30/25, 10:23 PM Check if a binary tree is subtree of another binary tree | Set 2 | GeeksforGeeks
286
Tree1: 1 4 2 3 5
Tree2: 1 4 2
Yes Tree2 is subroot of Tree1

Traversal taking O(n) and since we are also storing into the
string for checking its consuming O(n) space where n represents
the no. of node values

Time Complexity : O(n)

Auxiliary Space: O(n)

Interviewer: can you perform even better?

Yes we can use the KMP algorithm for string searching

Prerequisites : Please check the KMP algorithm first click here

Here is the implementation code using the KMP algorithm

class TreeNode {
constructor(val) {
this.val = val;
this.left = null;
this.right = null;
}
}

class Solution {
isSubtree(root, subRoot) {
return this.kmp(this.serialize(root), this.serialize(subRoot));
}

inOrderTraversal(root) {
if (!root) return;
this.inOrderTraversal(root.left);
console.log(root.val + " ");
this.inOrderTraversal(root.right);
}

kmp(s, p) {

https://www.geeksforgeeks.org/check-binary-tree-subtree-another-binary-tree-set-2/?ref=lbp 8/10
3/30/25, 10:23 PM Check if a binary tree is subtree of another binary tree | Set 2 | GeeksforGeeks
287
const lps = this.getLPS(p);
const n = s.length, m = p.length;
for (let i = 0, j = 0; i < n; ++i) {
while (s[i] !== p[j] && j > 0) j = lps[j-1];
if (s[i] === p[j]) j++;
if (j === m) return true;
}
return false;
}

getLPS(p) {
const m = p.length;
const lps = new Array(m);
for (let i = 1, j = 0; i < m; ++i) {
while (p[i] !== p[j] && j > 0) j = lps[j-1];
if (p[i] === p[j]) lps[i] = ++j;
}
return lps;
}

serialize(root) {
const str = [];
this.serializeHelper(root, str);
return str.join(",");
}

serializeHelper(root, str) {
if (!root) {
str.push("#");
} else {
str.push(root.val.toString());
this.serializeHelper(root.left, str);
this.serializeHelper(root.right, str);
}
}
}

const root = new TreeNode(3);


root.left = new TreeNode(4);
root.right = new TreeNode(5);
root.left.left = new TreeNode(1);
root.left.right = new TreeNode(2);

const subRoot = new TreeNode(4);


subRoot.left = new TreeNode(1);
subRoot.right = new TreeNode(2);

const myObj = new Solution();

https://www.geeksforgeeks.org/check-binary-tree-subtree-another-binary-tree-set-2/?ref=lbp 9/10
3/30/25, 10:23 PM Check if a binary tree is subtree of another binary tree | Set 2 | GeeksforGeeks
288
console.log("Our Tree1 and Tree2 Looks like:\n");
console.log("Tree1: ");
myObj.inOrderTraversal(root);
console.log("\nTree2: ");
myObj.inOrderTraversal(subRoot);
myObj.isSubtree(root, subRoot) ? console.log("\nYes Tree2 is subroot of T

Output

Our Tree1 and Tree2 Looks like:

Tree1: 1 4 2 3 5
Tree2: 1 4 2
Yes Tree2 is subroot of Tree1

Time Complexity : O(n)

Auxiliary Space : O(n)

https://www.geeksforgeeks.org/check-binary-tree-subtree-another-binary-tree-set-2/?ref=lbp 10/10
3/30/25, 10:23 PM Find largest subtree sum in a tree | GeeksforGeeks
289

Find largest subtree sum in a tree


Last Updated : 30 Oct, 2024

Given a Binary Tree, the task is to find a subtree with the maximum
sum in the tree.

Examples:

Input:

Output: 28
Explanation: As all the tree elements are positive, the largest
subtree sum is equal to sum of all tree elements.

Input:

https://www.geeksforgeeks.org/find-largest-subtree-sum-tree/?ref=lbp 1/6
3/30/25, 10:23 PM Find largest subtree sum in a tree | GeeksforGeeks
290

Output: 7
Explanation: Subtree with largest sum is:

Table of Content
[Expected Approach – 1] Using Recursion – O(n) Time and O(h)
Space
[Expected Approach – 2] Using BFS – O(n) Time and O(n) Space

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


Space

The idea is to do post order traversal of the binary tree. At every


node, find left subtree value and right subtree value recursively.
The value of subtree rooted at current node is equal to sum of
current node value, left node subtree sum and right node subtree
https://www.geeksforgeeks.org/find-largest-subtree-sum-tree/?ref=lbp 2/6
3/30/25, 10:23 PM Find largest subtree sum in a tree | GeeksforGeeks
291
sum. Compare current subtree sum with overall maximum
subtree sum so far.

Below is the implementation of the above approach:

C++ Java Python C# JavaScript

// JavaScript program to find largest subtree


// sum in a given binary tree.
class Node {
constructor(x) {
this.data = x;
this.left = null;
this.right = null;
}
}

// Helper function to find largest


// subtree sum recursively.
function findLargestSubtreeSumUtil(root, ans) {

// If current node is null then


// return 0 to parent node.
if (root === null)
return 0;

// Subtree sum rooted at current node.


let currSum = root.data +
findLargestSubtreeSumUtil(root.left, ans) +
findLargestSubtreeSumUtil(root.right, ans);

// Update answer if current subtree


// sum is greater than answer so far.
ans[0] = Math.max(ans[0], currSum);

// Return current subtree sum to


// its parent node.
return currSum;
}

// Function to find largest subtree sum.


function findLargestSubtreeSum(root) {

// If tree does not exist,


// then answer is 0.
if (root === null)
return 0;

// Variable to store maximum


// subtree sum.
let ans = [-Infinity];

// Call to recursive function to


// find maximum subtree sum.
findLargestSubtreeSumUtil(root, ans);
https://www.geeksforgeeks.org/find-largest-subtree-sum-tree/?ref=lbp 3/6
3/30/25, 10:23 PM Find largest subtree sum in a tree | GeeksforGeeks
292
return ans[0];
}

// Representation of the given tree


// 1
// / \
// -2 3
// / \ / \
// 4 5 -6 2
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);
root.right.left = new Node(-6);
root.right.right = new Node(2);

console.log(findLargestSubtreeSum(root));

Output

[Expected Approach – 2] Using BFS – O(n) Time and O(n)


Space

The idea is to use breadth first search to store nodes (level wise)
at each level in some container and then traverse these levels in
reverse order from bottom level to top level and keep storing the
subtree sum value rooted at nodes at each level. We can then
reuse these values for upper levels. Subtree sum rooted at node
= value of node + (subtree sum rooted at node->left) + (subtree
sum rooted at node->right)

Below is the implementation of the above approach:

C++ Java Python C# JavaScript

// JavaScript program to find largest subtree


// sum in a given binary tree using BFS
class Node {
constructor(x) {
this.data = x;
this.left = null;
this.right = null;
}

https://www.geeksforgeeks.org/find-largest-subtree-sum-tree/?ref=lbp 4/6
3/30/25, 10:23 PM Find largest subtree sum in a tree | GeeksforGeeks
293
}

function findLargestSubtreeSum(root) {

// Base case when tree is empty


if (root === null)
return 0;

let ans = Number.NEGATIVE_INFINITY;

// Queue for level order traversal


const q = [];

// Array of Array for storing


// nodes at a particular level
const levels = [];

// Map for storing sum of subtree


// rooted at a particular node
const subtreeSum = new Map();

// Push root to the queue


q.push(root);

while (q.length > 0) {

const n = q.length;

const level = [];

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


const node = q.shift();

// Push current node to current


// level array
level.push(node);

// Add left & right child of node


// in the queue
if (node.left)
q.push(node.left);
if (node.right)
q.push(node.right);
}

// add current level to levels array


levels.push(level);
}

// Traverse all levels from bottom most level to top


// most level
for (let i = levels.length - 1; i >= 0; i--) {

for (const e of levels[i]) {

// add value of current node


subtreeSum.set(e, e.data);

// If node has left child, add the subtree sum

https://www.geeksforgeeks.org/find-largest-subtree-sum-tree/?ref=lbp 5/6
3/30/25, 10:23 PM Find largest subtree sum in a tree | GeeksforGeeks
294
// of subtree rooted at left child
if (e.left)
subtreeSum.set(e, subtreeSum.get(e)
+ subtreeSum.get(e.left));

// If node has right child, add the subtree sum


// of subtree rooted at right child
if (e.right)
subtreeSum.set(e, subtreeSum.get(e)
+ subtreeSum.get(e.right));

// update ans to maximum of ans and sum of


// subtree rooted at current node
ans = Math.max(ans, subtreeSum.get(e));
}
}

return ans;
}

// Representation of the given tree


// 1
// / \
// -2 3
// / \ / \
// 4 5 -6 2
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(2);

console.log(findLargestSubtreeSum(root));

Output

https://www.geeksforgeeks.org/find-largest-subtree-sum-tree/?ref=lbp 6/6
3/30/25, 10:24 PM Maximum sum of nodes in Binary tree such that no two are adjacent | GeeksforGeeks
295

Maximum sum of nodes in Binary tree such that


no two are adjacent
Last Updated : 25 Nov, 2024

Given a binary tree with a value associated with each node, we need
to choose a subset of these nodes such that the sum of selected
nodes is maximum under a constraint that no two chosen nodes in
the subset should be directly connected, that is, if we have taken a
node in our sum then we can’t take any of its children in consideration
and vice versa.

Examples:

Input:

Output: 11
Explanation: The maximum sum is sum of node 11.

https://www.geeksforgeeks.org/maximum-sum-nodes-binary-tree-no-two-adjacent/?ref=lbp 1/8
3/30/25, 10:24 PM Maximum sum of nodes in Binary tree such that no two are adjacent | GeeksforGeeks
296

Input:

Output: 16
Explanation: The maximum sum is sum of nodes 1 4 5 6 , i.e 16.
These nodes are non adjacent.

https://www.geeksforgeeks.org/maximum-sum-nodes-binary-tree-no-two-adjacent/?ref=lbp 2/8
3/30/25, 10:24 PM Maximum sum of nodes in Binary tree such that no two are adjacent | GeeksforGeeks
297

Table of Content
Using Recursion – O(2^n) Time and O(n) Space
Using pair – O(n) Time and O(h) Space
Using Top-Down DP (Memoization) – O(n) Time and O(n) Space

Using Recursion – O(2^n) Time and O(n) Space

We can solve this problem by considering the fact that both


node and its children can’t be in sum at the same time, so when
we take a node into our sum, we will call recursively for its
grandchildren or if we don’t take this node then we will call for
all its children nodes and finally we will choose maximum from
both of the results.

For each node in the binary tree, calculate two sums:


Include the current node: Add the current node’s value
and the maximum sums of its grandchildren.
Exclude the current node: Sum the maximum sums of its
left and right children.
Use a recursive function to compute these sums for each node.
For each node, take the maximum of the two sums (including or
excluding the node).
The result for the root node is the maximum sum of non-adjacent
nodes in the entire tree.
https://www.geeksforgeeks.org/maximum-sum-nodes-binary-tree-no-two-adjacent/?ref=lbp 3/8
3/30/25, 10:24 PM Maximum sum of nodes in Binary tree such that no two are adjacent | GeeksforGeeks
298
C++ Java Python C# JavaScript

// JavaScript program to find the maximum sum


// of non-adjacent nodes in a binary tree.

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

// Utility method to return the maximum sum


// rooted at the node 'node'
function getMaxSumUtil(node) {
if (node === null) {

// If the node is null, the sum is 0


return 0;
}

// Calculate the maximum sum including the


// current node
let incl = node.data;

// If the left child exists, include its contribution


if (node.left) {
incl += getMaxSumUtil(node.left.left) +
getMaxSumUtil(node.left.right);
}

// If the right child exists, include its contribution


if (node.right) {
incl += getMaxSumUtil(node.right.left) +
getMaxSumUtil(node.right.right);
}

// Calculate the maximum sum excluding


// the current node
let excl = 0;
if (node.left) {
excl += getMaxSumUtil(node.left);
}
if (node.right) {
excl += getMaxSumUtil(node.right);
}

// The result for the current node is the


// maximum of including or excluding it
return Math.max(incl, excl);
}

function getMaxSum(root) {

// If the tree is empty, the maximum sum is 0


if (root === null) return 0;

https://www.geeksforgeeks.org/maximum-sum-nodes-binary-tree-no-two-adjacent/?ref=lbp 4/8
3/30/25, 10:24 PM Maximum sum of nodes in Binary tree such that no two are adjacent | GeeksforGeeks
299
// Call the utility function to compute
// the maximum sum for the entire tree
return getMaxSumUtil(root);
}

// Creating a binary tree with the following structure:


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

console.log(getMaxSum(root));

Output

11

Using pair – O(n) Time and O(h) Space

Return a pair for each node in the binary tree such that the first
of the pair indicates the maximum sum when the data of a node
is included and the second indicates the maximum sum when
the data of a particular node is not included.

C++ Java Python C# JavaScript

// JavaScript program to find the maximum sum in a Binary Tree


// such that no two nodes are adjacent.

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

// Helper function to find the maximum sum


function maxSumHelper(root) {
if (root === null) {
return [0, 0];
}

https://www.geeksforgeeks.org/maximum-sum-nodes-binary-tree-no-two-adjacent/?ref=lbp 5/8
3/30/25, 10:24 PM Maximum sum of nodes in Binary tree such that no two are adjacent | GeeksforGeeks
300
// Recursively get the maximum sum for left and right subtrees
const leftSum = maxSumHelper(root.left);
const rightSum = maxSumHelper(root.right);

// This node is included (children are not included)


const include = leftSum[1] + rightSum[1] + root.data;

// This node is excluded (children may be included)


const exclude = Math.max(leftSum[0], leftSum[1]) +
Math.max(rightSum[0], rightSum[1]);

return [include, exclude];


}

// Function to get the maximum sum with the given constraints


function getMaxSum(root) {
const result = maxSumHelper(root);
return Math.max(result[0], result[1]);
}

// Creating a binary tree with the following structure:


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

console.log(getMaxSum(root));

Output

11

Using Top-Down DP (Memoization) – O(n) Time and O(n)


Space

The naive approach leads to recalculating results for the same


nodes multiple times. For example, if we include the root node,
we recursively compute the sum for its grandchildren (nodes 4
and 5). But if we exclude the root, we compute the sum for its
children, and node 3 also computes the sum for its children (4
and 5 again).

https://www.geeksforgeeks.org/maximum-sum-nodes-binary-tree-no-two-adjacent/?ref=lbp 6/8
3/30/25, 10:24 PM Maximum sum of nodes in Binary tree such that no two are adjacent | GeeksforGeeks
301
To avoid this redundancy, we use memoization:

We store the result of each node in a hashmap.


When a node’s value is needed again, we directly return it
from the map instead of recalculating.

C++ Java Python C# JavaScript

// JavaScript program to find the maximum sum of


// non-adjacent nodes in a binary tree using memoization.

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

// Utility method to return the maximum sum


// rooted at the node 'node'
function getMaxSumUtil(node, memo) {
if (node === null) {

// If the node is null, the sum is 0


return 0;
}

// If the result is already computed, return it from memo


if (memo.has(node)) {
return memo.get(node);
}

// Calculate the maximum sum including the current node


let incl = node.data;

// If the left child exists, include its grandchildren


if (node.left) {
incl += getMaxSumUtil(node.left.left, memo) +
getMaxSumUtil(node.left.right, memo);
}

// If the right child exists, include its grandchildren


if (node.right) {
incl += getMaxSumUtil(node.right.left, memo) +
getMaxSumUtil(node.right.right, memo);
}

// Calculate the maximum sum excluding the


// current node
let excl = getMaxSumUtil(node.left, memo) +
getMaxSumUtil(node.right, memo);

https://www.geeksforgeeks.org/maximum-sum-nodes-binary-tree-no-two-adjacent/?ref=lbp 7/8
3/30/25, 10:24 PM Maximum sum of nodes in Binary tree such that no two are adjacent | GeeksforGeeks
302
// Store the result in memo and return
memo.set(node, Math.max(incl, excl));
return memo.get(node);
}

// Function to compute the maximum sum of


// non-adjacent nodes
function getMaxSum(root) {
let memo = new Map();
return getMaxSumUtil(root, memo);
}

// Creating a binary tree with the following structure:


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

console.log(getMaxSum(root));

Output

11

https://www.geeksforgeeks.org/maximum-sum-nodes-binary-tree-no-two-adjacent/?ref=lbp 8/8
3/30/25, 10:24 PM Lowest Common Ancestor in a Binary Tree | GeeksforGeeks
303

Lowest Common Ancestor in a Binary Tree


Last Updated : 17 Dec, 2024

Given the root of a Binary Tree with all unique values and two node
values n1 and n2, the task is to find the lowest common ancestor of
the given two nodes. The Lowest Common Ancestor (or LCA) is the
lowest node in the tree that has both n1 and n2 as descendants. In
other words, the LCA of n1 and n2 is the shared ancestor of n1 and n2
that is located farthest from the root.

We may assume that either both n1 and n2 are present in the tree or
none of them are present.

Examples:

Input:

Output: 2
Explanation: As shown below, LCA of 4 and 5 is 2

https://www.geeksforgeeks.org/lowest-common-ancestor-binary-tree-set-1/?ref=lbp 1/11
3/30/25, 10:24 PM Lowest Common Ancestor in a Binary Tree | GeeksforGeeks
304

Input:

Output: 1
Explanation: As shown below, LCA of 5 and 6 is 1.

https://www.geeksforgeeks.org/lowest-common-ancestor-binary-tree-set-1/?ref=lbp 2/11
3/30/25, 10:24 PM Lowest Common Ancestor in a Binary Tree | GeeksforGeeks
305

Table of Content
Using Arrays to Store Paths of Nodes from Root – O(n) Time and
O(n) Space
[Expected Approach] Using Single Traversal – O(n) Time and O(h)
Space
Alternate Approach – O(n) Time and O(h) Space
Application of Lowest Common Ancestor(LCA)

Using Arrays to Store Paths of Nodes from Root – O(n) Time


and O(n) Space

The idea is to store the paths of nodes from the root in two
separate arrays. Then start traversing from the 0th index and
look simultaneously into the values stored in the arrays, the LCA
is the last matching element in both the arrays.

https://www.geeksforgeeks.org/lowest-common-ancestor-binary-tree-set-1/?ref=lbp 3/11
3/30/25, 10:24 PM Lowest Common Ancestor in a Binary Tree | GeeksforGeeks
306

Path from root to 5 = 1 -> 2 -> 5


Path from root to 6 = 1 -> 3 -> 6

We start checking from 0th index. As both of the value


matches, we move to the next index.
Now check for values at 1st index, there’s a mismatch so we
consider the previous value.
Therefore the LCA of (5, 6) is 1

C++ Java Python C# JavaScript

// Javascript program to find LCA using Arrays to Store


// Paths of Nodes from Root

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

// Function to find path from root to given node.


function findPath(root, path, k) {

// base case
if (root === null)
return false;

// Store current node value in the path.


path.push(root);

// If node value is equal to k, or


// if node exists in left subtree or
https://www.geeksforgeeks.org/lowest-common-ancestor-binary-tree-set-1/?ref=lbp 4/11
3/30/25, 10:24 PM Lowest Common Ancestor in a Binary Tree | GeeksforGeeks
307
// if node exists in right subtree return true
if (root.data === k ||
findPath(root.left, path, k) ||
findPath(root.right, path, k))
return true;

// else remove root from path and return false


path.pop();
return false;
}

// Returns LCA of two nodes.


function lca(root, n1, n2) {

// to store paths to n1 and n2 from the root


let path1 = [];
let path2 = [];

// Find paths from root to n1 and


// root to n2. If either
// n1 or n2 is not present, return null
if (!findPath(root, path1, n1) ||
!findPath(root, path2, n2))
return null;

// Compare the paths to get the first


// different value
let i;
for (i = 0; i < path1.length && i < path2.length; i++) {
if (path1[i] !== path2[i])
return path1[i - 1];
}

// if both the datas are same, return last node


return path1[i - 1];
}

// construct the binary tree


// 1
// / \
// 2 3
// / \ / \
// 4 5 6 7
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);
root.right.left = new Node(6);
root.right.right = new Node(7);

let ans = lca(root, 4, 5);


if (ans === null)
console.log("No common ancestor found");
else
console.log(ans.data);

https://www.geeksforgeeks.org/lowest-common-ancestor-binary-tree-set-1/?ref=lbp 5/11
3/30/25, 10:24 PM Lowest Common Ancestor in a Binary Tree | GeeksforGeeks
308

Output

[Expected Approach] Using Single Traversal – O(n) Time and


O(h) Space

Note: This approach assumes that both the keys are present in the
given tree.

The idea is to traverse the tree starting from the root. If any of
the given keys (n1 and n2) matches with the root, then the root
is LCA (assuming that both keys are present). If the root doesn’t
match with any of the keys, we recur for the left and right
subtree. The node which has one key present in its left subtree
and the other key present in the right subtree is the LCA, else if,
both keys lie in the left subtree, then the left subtree has LCA,
else the LCA lies in the right subtree.

Illustration:

Root is pointing to the node with value 1, as its value doesn’t


match with { 5, 6 }. We look for the key in left subtree and right
subtree.

Left Subtree :

https://www.geeksforgeeks.org/lowest-common-ancestor-binary-tree-set-1/?ref=lbp 6/11
3/30/25, 10:24 PM Lowest Common Ancestor in a Binary Tree | GeeksforGeeks
309
New Root = { 2 } ≠ 5 or 6, hence we will continue our
recursion
New Root = { 4 } , it’s left and right subtree is null,
we will return NULL for this call
New Root = { 5 } , value matches with 5 so will return
the node with value 5
The function call for root with value 2 will return a
value of 5
Right Subtree :
Root = { 3 } ≠ 5 or 6 hence we continue our recursion
Root = { 6 } = 5 or 6 , we will return the this node
with value 6
Root = { 7 } ≠ 5 or 6, we will return NULL
So the function call for root with value 3 will return
node with value 6
As both the left subtree and right subtree of the node with
value 1 is not NULL, so 1 is the LCA.

C++ C Java Python C# JavaScript

// Javascript program to find LCA using Single traversal

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

// Function to find LCA of two keys.


function lca(root, n1, n2) {

if (root === null)


return null;

// If either key matches with root data, return root


if (root.data === n1 || root.data === n2)
return root;

// Look for data in left and right subtrees


let leftLca = lca(root.left, n1, n2);
let rightLca = lca(root.right, n1, n2);

https://www.geeksforgeeks.org/lowest-common-ancestor-binary-tree-set-1/?ref=lbp 7/11
3/30/25, 10:24 PM Lowest Common Ancestor in a Binary Tree | GeeksforGeeks
310
// If both of the above calls return Non-NULL, then one
// data is present in one subtree and the other is present
// in the other, so this node is the LCA
if (leftLca && rightLca)
return root;

// Otherwise check if left subtree or right subtree is LCA


return leftLca ? leftLca : rightLca;
}

// Construct the binary tree


// 1
// / \
// 2 3
// / \ / \
// 4 5 6 7

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);
root.right.left = new Node(6);
root.right.right = new Node(7);

let ans = lca(root, 4, 5);


if (ans === null) {
console.log("No common ancestor found");
}
else {
console.log(ans.data);
}

Output

Alternate Approach – O(n) Time and O(h) Space

The above method assumes that keys are present in Binary Tree.
If one key is present and the other is absent, then it returns the
present key as LCA, whereas it ideally should have returned
NULL. We can extend the above method to handle all cases by
checking if n1 and n2 are present in the tree first and then
finding the LCA of n1 and n2. To check whether the node is
present in the binary tree or not then traverse on the tree for
both n1 and n2 nodes separately.

https://www.geeksforgeeks.org/lowest-common-ancestor-binary-tree-set-1/?ref=lbp 8/11
3/30/25, 10:24 PM Lowest Common Ancestor in a Binary Tree | GeeksforGeeks
311
C++ Java Python C# JavaScript

// JavaScript Program to find LCA

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

// Function to find LCA of two datas.


function findLca(root, n1, n2) {

if (!root)
return null;

// If either data matches with root data, return root


if (root.data === n1 || root.data === n2)
return root;

// Look for datas in left and right subtrees


var leftLca = findLca(root.left, n1, n2);
var rightLca = findLca(root.right, n1, n2);

// If both of the above calls return Non-NULL, then one


// data is present in one subtree and the other is present
// in the other, so this node is the LCA
if (leftLca && rightLca)
return root;

// Otherwise check if left subtree or right subtree is


// LCA
return leftLca ? leftLca : rightLca;
}

// Returns true if key k is present in tree rooted with root


function checkIfPresent(root, k) {

// Base Case
if (root == null)
return false;

// If data is present at root, or in left subtree or


// right subtree, return true;
if (root.data === k || checkIfPresent(root.left, k) ||
checkIfPresent(root.right, k))
return true;

// Else return false


return false;
}

// Function to check if keys are present


// in the tree and returns the lca.
function lca(root, n1, n2) {

https://www.geeksforgeeks.org/lowest-common-ancestor-binary-tree-set-1/?ref=lbp 9/11
3/30/25, 10:24 PM Lowest Common Ancestor in a Binary Tree | GeeksforGeeks
312
// Return LCA only if both n1 and n2 are
// present in tree
if (checkIfPresent(root, n1) && checkIfPresent(root, n2))
return findLca(root, n1, n2);

// Else return null


return null;
}

// construct the binary tree


// 1
// / \
// 2 3
// / \ / \
// 4 5 6 7

var 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);

var ans = lca(root, 4, 5);


if (ans === null) {
console.log("No common ancestor found");
}
else {
console.log(ans.data);
}

Output

Application of Lowest Common Ancestor(LCA)

We use LCA to find the shortest distance between pairs of nodes in a


tree: the shortest distance from n1 to n2 can be computed as the
distance from the LCA to n1, plus the distance from the LCA to n2.

Related articles:

LCA using Parent Pointer


Lowest Common Ancestor in a Binary Search Tree.
Find LCA in Binary Tree using RMQ

https://www.geeksforgeeks.org/lowest-common-ancestor-binary-tree-set-1/?ref=lbp 10/11
3/30/25, 10:24 PM Lowest Common Ancestor in a Binary Tree | GeeksforGeeks
313

https://www.geeksforgeeks.org/lowest-common-ancestor-binary-tree-set-1/?ref=lbp 11/11
3/30/25, 10:24 PM Height of a generic tree from parent array | GeeksforGeeks
314

Height of a generic tree from parent array


Last Updated : 01 Nov, 2024

Given a tree of size n as array parent[0..n-1] where every index i in


the parent[] represents a node and the value at i represents the
immediate parent of that node. For root, the node value will be -1.
Find the height of the generic tree given the parent links.

Examples:

Input: parent[] = [-1, 0, 0, 0, 3, 1, 1, 2]


Output : 2

Input: parent[] = [-1, 0, 1, 2, 3]


Output : 4

https://www.geeksforgeeks.org/height-generic-tree-parent-array/?ref=lbp 1/7
3/30/25, 10:24 PM Height of a generic tree from parent array | GeeksforGeeks
315

Here, a generic tree is sometimes also called an N-ary tree or N-


way tree where N denotes the maximum number of child a node
can have. In this problem, the array represents n number of
nodes in the tree.

The naive approach is to traverse up the tree from the node till the
root node is reached with node value -1. While Traversing for each
node stores maximum path length. The Time Complexity of this
solution is O(n^2).

Table of Content
[Expected Approach – 1] Using BFS – O(n) Time and O(n) Space
[Expected Approach – 2] Without using map – O(n) Time and O(n)
Space

[Expected Approach – 1] Using BFS – O(n) Time and O(n)


Space

Build graph for N-ary Tree in O(n) time and apply BFS on the
stored graph in O(n) time and while doing BFS store maximum
reached level. This solution does two iterations to find the
height of N-ary tree.

Below is the implementation of the above approach:

https://www.geeksforgeeks.org/height-generic-tree-parent-array/?ref=lbp 2/7
3/30/25, 10:24 PM Height of a generic tree from parent array | GeeksforGeeks
316
C++ Java Python C# JavaScript

// JavaScript code to find the height of an N-ary tree using


// BFS

function buildTree(parent) {
let adj
= Array.from({length : parent.length}, () => []);
let root = -1;

// Iterate through all nodes to establish


// connections
for (let i = 0; i < parent.length; i++) {
if (parent[i] === -1)
root = i;
else {
adj[i].push(parent[i]);
adj[parent[i]].push(i);
}
}
return {root, adj};
}

// Function to compute height of the


// tree using BFS
function getTreeHeight(root, adj) {
let visited = new Set();
let q = [ [ root, 0 ] ];
let maxHeight = 0;

// Start BFS from the root node


while (q.length) {
let [node, level] = q.shift();
visited.add(node);
maxHeight = Math.max(maxHeight, level);

// Traverse all children of the


// current node
for (let child of adj[node]) {
if (!visited.has(child)) {

// Increment level
q.push([ child, level + 1 ]);
}
}
}

return maxHeight;
}

const parent = [ -1, 0, 0, 0, 3, 1, 1, 2 ];


const {root, adj} = buildTree(parent);
const height = getTreeHeight(root, adj);
console.log(height);

Output
https://www.geeksforgeeks.org/height-generic-tree-parent-array/?ref=lbp 3/7
3/30/25, 10:24 PM Height of a generic tree from parent array | GeeksforGeeks
317
2

[Expected Approach – 2] Without using map – O(n) Time and


O(n) Space

We can find the height of the N-ary Tree in only one iteration.
We visit nodes from 0 to n-1 iteratively and mark the unvisited
ancestors recursively if they are not visited before till we reach a
node which is visited, or we reach the root node. If we reach the
visited node while traversing up the tree using parent links, then
we use its height and will not go further in recursion.

Explanation For Example 1:

For node 0: Check for Root node is true,


Return 0 as height, Mark node 0 as visited
For node 1: Recur for an immediate ancestor, i.e 0, which is
already visited
So, Use its height and return height(node 0) +1
Mark node 1 as visited
For node 2: Recur for an immediate ancestor, i.e 0, which is
already visited

https://www.geeksforgeeks.org/height-generic-tree-parent-array/?ref=lbp 4/7
3/30/25, 10:24 PM Height of a generic tree from parent array | GeeksforGeeks
318
So, Use its height and return height(node 0) +1
Mark node 2 as visited
For node 3: Recur for an immediate ancestor, i.e 0, which is
already visited
So, Use its height and return height(node 0) +1
Mark node 3 as visited
For node 4: Recur for an immediate ancestor, i.e 3, which is
already visited
So, Use its height and return height(node 3) +1
Mark node 3 as visited
For node 5: Recur for an immediate ancestor, i.e 1, which is
already visited
So, Use its height and return height(node 1) +1
Mark node 5 as visited
For node 6: Recur for an immediate ancestor, i.e 1, which is
already visited
So, Use its height and return height(node 1) +1
Mark node 6 as visited
For node 7: Recur for an immediate ancestor, i.e 2, which is
already visited
So, Use its height and return height(node 2) +1
Mark node 7 as visited
Hence, we processed each node in the N-ary tree only once.

Below is the implementation of the above approach:

C++ Java Python C# JavaScript

// Javascript code of finding height of N-array


// tree

function fillHeight(parent, node, visited, height) {

// If root node
if (parent[node] === -1) {

// mark root node as visited


visited[node] = 1;
return 0;
}
https://www.geeksforgeeks.org/height-generic-tree-parent-array/?ref=lbp 5/7
3/30/25, 10:24 PM Height of a generic tree from parent array | GeeksforGeeks
319
// If node is already visited
if (visited[node])
return height[node];

// Visit node and calculate its height


visited[node] = 1;

// Recur for the parent node


height[node] = 1
+ fillHeight(parent, parent[node],
visited, height);

// Return calculated height for node


return height[node];
}

function findHeight(parent) {

let n = parent.length;

// To store max height


let maxHeight = 0;

// To check whether or not node


// is visited before
let visited = Array(n).fill(0);

// For storing the height of each node


let height = Array(n).fill(0);

// Calculate the height of all nodes


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

// If not visited before


if (!visited[i])
height[i]
= fillHeight(parent, i, visited, height);

// Store maximum height so far


maxHeight = Math.max(maxHeight, height[i]);
}

return maxHeight;
}

let parent = [ -1, 0, 0, 0, 3, 1, 1, 2 ];


console.log(findHeight(parent));

Output

https://www.geeksforgeeks.org/height-generic-tree-parent-array/?ref=lbp 6/7
3/30/25, 10:24 PM Height of a generic tree from parent array | GeeksforGeeks
320

https://www.geeksforgeeks.org/height-generic-tree-parent-array/?ref=lbp 7/7
3/30/25, 10:25 PM Find distance between two nodes of a Binary Tree | GeeksforGeeks
321

Find distance between two nodes of a Binary Tree


Last Updated : 09 Oct, 2024

Given a Binary tree, the task is to find the distance between two keys
in a binary tree, no parent pointers are given. The distance between
two nodes is the minimum number of edges to be traversed to reach
one node from another. The given two nodes are guaranteed to be in
the binary tree and all node values are unique.

Table of Content
Using LCA and Path Length – O(n) Time and O(h) Space
Using LCA – O(n) Time and O(h) Space
Using LCA (one pass) – O(n) Time and O(h) Space

Using LCA and Path Length – O(n) Time and O(h) Space

The idea to first find the Lowest Common Ancestor (LCA) of two
given nodes in a binary tree. Once the LCA is found, we calculate
the distance between the two target nodes by finding the path
length from the root to each node and then subtracting twice
the path length from the root to the LCA.

https://www.geeksforgeeks.org/find-distance-between-two-nodes-of-a-binary-tree/?ref=lbp 1/9
3/30/25, 10:25 PM Find distance between two nodes of a Binary Tree | GeeksforGeeks
322

Dist(n1, n2) = Dist(root, n1) + Dist(root, n2) – 2*Dist(root, lca)

n1′ and ‘n2’ are the two given keys


‘root’ is root of given Binary Tree.
‘lca’ is lowest common ancestor of n1 and n2
Dist(n1, n2) is the distance between n1 and n2.

Step-By-Step Implementation :

Start by traversing the tree to find the level of the first target node.
If the node is found, return its level; otherwise, continue searching
recursively in the left and right subtrees.
Recursively check each node to see if it matches either of the target
nodes. If a match is found, store the current level. If both nodes are
located in different subtrees, calculate the distance based on their
levels.
If only one of the target nodes is found, determine the distance to
the other node using the level obtained from the LCA. This involves
further traversals to find the level of the remaining target node.
Using the levels obtained, compute the total distance between the
two nodes by adding their levels and subtracting twice the level of
the LCA. This gives the direct distance between the two target
nodes.
Finally, return the calculated distance.

Below is the implementation of the above approach.

C++ C Java Python C# JavaScript

// JavaScript Program to Find distance between


// two nodes of a Binary Tree

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

https://www.geeksforgeeks.org/find-distance-between-two-nodes-of-a-binary-tree/?ref=lbp 2/9
3/30/25, 10:25 PM Find distance between two nodes of a Binary Tree | GeeksforGeeks
323
// Function to find the level of a node
function findLevel(root, k, level) {
if (root === null) return -1;
if (root.data === k) return level;

// Recursively call function on left child


const leftLevel = findLevel(root.left, k, level + 1);

// If node is found on left, return level


// Else continue searching on the right child
if (leftLevel !== -1) {
return leftLevel;
} else {
return findLevel(root.right, k, level + 1);
}
}

// Function to find the lowest common ancestor


// and calculate distance between two nodes
function findLcaAndDistance(root, a, b, d1, d2, dist, lvl) {
if (root === null) return null;

if (root.data === a) {

// If first node found, store level and


// return the node
d1[0] = lvl;
return root;
}
if (root.data === b) {

// If second node found, store level and


// return the node
d2[0] = lvl;
return root;
}

// Recursively call function on left child


const left = findLcaAndDistance
(root.left, a, b, d1, d2, dist, lvl + 1);

// Recursively call function on right child


const right = findLcaAndDistance
(root.right, a, b, d1, d2, dist, lvl + 1);

if (left !== null && right !== null) {

// If both nodes are found in different


// subtrees, calculate the distance
dist[0] = d1[0] + d2[0] - 2 * lvl;
}

// Return node found or null if not found


if (left !== null) {
return left;
} else {
return right;
}

https://www.geeksforgeeks.org/find-distance-between-two-nodes-of-a-binary-tree/?ref=lbp 3/9
3/30/25, 10:25 PM Find distance between two nodes of a Binary Tree | GeeksforGeeks
324
}

// Function to find distance between two nodes


function findDist(root, a, b) {
const d1 = [-1];
const d2 = [-1];
const dist = [0];

// Find lowest common ancestor and calculate distance


const lca = findLcaAndDistance(root, a, b, d1, d2, dist, 1);

if (d1[0] !== -1 && d2[0] !== -1) {

// Return the distance if both nodes are found


return dist[0];
}

if (d1[0] !== -1) {

// If only first node is found, find


// distance to second node
dist[0] = findLevel(lca, b, 0);
return dist[0];
}

if (d2[0] !== -1) {

// If only second node is found, find


// distance to first node
dist[0] = findLevel(lca, a, 0);
return dist[0];
}

// Return -1 if both nodes not found


return -1;
}

// Hardcoded binary tree


// 1
// / \
// 2 3
// / \ / \
// 4 5 6 7

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

const a = 4;
const b = 7;

console.log(findDist(root, a, b));

https://www.geeksforgeeks.org/find-distance-between-two-nodes-of-a-binary-tree/?ref=lbp 4/9
3/30/25, 10:25 PM Find distance between two nodes of a Binary Tree | GeeksforGeeks
325

Output

Using LCA – O(n) Time and O(h) Space

The idea is to first identify their Lowest Common Ancestor


(LCA). Once the LCA is determined, the distance between each
node and the LCA is calculated. The sum of these distances
gives the total distance between the two nodes

Step-By-Step Implementation :

Start at the root of the tree and recursively traverse the left and
right subtrees. If the current node is null, return null. If the current
node matches either of the two nodes, return the current node. If
both left and right subtree calls return non-null values, the current
node is the LCA.
From the LCA node, find the level of the first node. If the current
node matches the target, return the current depth. Recursively
check both the left and right children, increasing the depth by one
until the node is found.
Perform the same level calculation for the second node. Collect the
depth values for both nodes, which represent the distance from the
LCA to each of the two nodes.
Sum the distances obtained from the previous steps. This total
represents the distance between the two nodes in the binary tree,
giving the final result.

Below is the implementation of the above approach.

C++ C Java Python C# JavaScript

// JavaScript Program to Find distance between two


// nodes of a Binary Tree

class Node {
constructor(key) {

https://www.geeksforgeeks.org/find-distance-between-two-nodes-of-a-binary-tree/?ref=lbp 5/9
3/30/25, 10:25 PM Find distance between two nodes of a Binary Tree | GeeksforGeeks
326
this.data = key;
this.left = null;
this.right = null;
}
}

// Function to find the Lowest Common Ancestor


// (LCA) of two nodes
function lca(root, n1, n2) {
if (root === null) {
return root;
}

if (root.data === n1 || root.data === n2) {


return root;
}

let left = lca(root.left, n1, n2);


let right = lca(root.right, n1, n2);

if (left !== null && right !== null) {


return root;
}

if (left === null && right === null) {


return null;
}

return left !== null ? left : right;


}

// Returns level of key k if it is present in tree,


// otherwise returns -1
function findLevel(root, k, level) {
if (root === null) {
return -1;
}

if (root.data === k) {
return level;
}

let left = findLevel(root.left, k, level + 1);


if (left === -1) {
return findLevel(root.right, k, level + 1);
}

return left;
}

// Function to find distance between two


// nodes in a binary tree
function findDistance(root, a, b) {
let lcaNode = lca(root, a, b);

let d1 = findLevel(lcaNode, a, 0);


let d2 = findLevel(lcaNode, b, 0);

return d1 + d2;

https://www.geeksforgeeks.org/find-distance-between-two-nodes-of-a-binary-tree/?ref=lbp 6/9
3/30/25, 10:25 PM Find distance between two nodes of a Binary Tree | GeeksforGeeks
327
}

// Create a sample tree:


// 1
// / \
// 2 3
// / \ / \
// 4 5 6 7

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);
root.right.left = new Node(6);
root.right.right = new Node(7);

console.log(findDistance(root, 4, 7));

Output

Using LCA (one pass) – O(n) Time and O(h) Space

We first find the LCA of two nodes. Then we find the distance
from LCA to two nodes. We know that distance between two
node(let suppose n1 and n2) = distance between LCA and n1 +
distance between LCA and n2.

Step-By-Step Implementation :

Recursively traverses the tree to find the distance between the two
target nodes. During traversal, check if the current node is one of
the target nodes.
While traversing, if one of the target nodes is found, check if there
are any descendants of the other target node. This will help in
determining whether to continue counting the distance or to reset
it.
If both target nodes are found in the left and right subtrees of the
current node, that node is their LCA. At this point, calculate the
distance from the LCA to each target node.

https://www.geeksforgeeks.org/find-distance-between-two-nodes-of-a-binary-tree/?ref=lbp 7/9
3/30/25, 10:25 PM Find distance between two nodes of a Binary Tree | GeeksforGeeks
328
After calculating the distances from the LCA to both target nodes,
return their sum as the final distance between the two nodes in the
binary tree.

Below is the implementation of the above approach.

C++ C Java Python C# JavaScript

// JavaScript Program to Find distance between


// two nodes of a Binary Tree

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

// Function that calculates distance between two nodes.


// It returns an object where the first property indicates
// whether n1 or n2 is found and the second property
// is the distance from the current node.
function calculateDistance(root, n1, n2, distance) {
if (!root) return { found: false, dist: 0 };

let left = calculateDistance(root.left, n1, n2, distance);


let right = calculateDistance(root.right, n1, n2, distance);

let current = (root.data === n1 || root.data === n2);

if (current && (left.found || right.found)) {


distance.value = Math.max(left.dist, right.dist);
return { found: false, dist: 0 };
}

if (left.found && right.found) {


distance.value = left.dist + right.dist;
return { found: false, dist: 0 };
}

if (left.found || right.found || current) {


return { found: true, dist:
Math.max(left.dist, right.dist) + 1 };
}

return { found: false, dist: 0 };


}

// The function that returns distance


// between n1 and n2.
function findDistance(root, n1, n2) {
let distance = { value: 0 };
calculateDistance(root, n1, n2, distance);
return distance.value;

https://www.geeksforgeeks.org/find-distance-between-two-nodes-of-a-binary-tree/?ref=lbp 8/9
3/30/25, 10:25 PM Find distance between two nodes of a Binary Tree | GeeksforGeeks
329
}

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);
root.right.left = new Node(6);
root.right.right = new Node(7);

// 1
// / \
// 2 3
// / \ / \
// 4 5 6 7

console.log(findDistance(root, 4, 7));

Output

https://www.geeksforgeeks.org/find-distance-between-two-nodes-of-a-binary-tree/?ref=lbp 9/9
3/30/25, 10:25 PM Modify a binary tree to get preorder traversal using right pointers only | GeeksforGeeks
330

Modify a binary tree to get preorder traversal


using right pointers only
Last Updated : 29 Oct, 2024

Given a binary tree. The task is to modify it in such a way that after
modification preorder traversal of it can get only with the right
pointers. During modification, we can use right as well as left
pointers.

Examples:

Input :

Output :

https://www.geeksforgeeks.org/modify-binary-tree-get-preorder-traversal-using-right-pointers/?ref=lbp 1/5
3/30/25, 10:25 PM Modify a binary tree to get preorder traversal using right pointers only | GeeksforGeeks
331

Explanation: The preorder traversal of given binary tree is 10 8 3


5 2.

Table of Content
[Expected Approach – 1] Using recursion – O(n) Time and O(h)
Space
[Expected Approach – 2] Using Iterative Preorder Traversal – O(n)
Time and O(n) Space

[Expected Approach – 1] Using recursion – O(n) Time and O(h)


Space

The idea is to use recursion to transform the tree, the right


pointer of the root is made to point to the left subtree. If the
node has only a left child, the left child is moved to the right,
completing the processing for that node. However, if the node
has both left and right children, the original right child is moved
to the rightmost node of the left subtree. This process ensures
that the entire left subtree is shifted to the right, and the
rightmost node of the transformed subtree is returned after the
node is processed.

Below is the implementation of the above approach:

C++ Java Python C# JavaScript

// JavaScript code to modify binary tree for traversal using


https://www.geeksforgeeks.org/modify-binary-tree-get-preorder-traversal-using-right-pointers/?ref=lbp 2/5
3/30/25, 10:25 PM
// p
Modify a binary tree to get preorder traversal using right pointers only | GeeksforGeeks
fy y f g 332
// only right pointer

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

// Function to modify tree


function modifytree(root) {

let right = root.right;


let rightMost = root;

// If the left tree exists


if (root.left) {

// Get the right-most of the original


// left subtree
rightMost = modifytree(root.left);

// Set root right to left subtree


root.right = root.left;
root.left = null;
}

// If the right subtree does not


// exist we are done!
if (!right)
return rightMost;

// Set right pointer of right-most of


//the original left subtree
rightMost.right = right;

// Modify the right subtree


rightMost = modifytree(right);
return rightMost;
}

function printpre(curr) {
while (curr != null) {
console.log(curr.data + " ");
curr = curr.right;
}
}

let 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);

modifytree(root);
printpre(root);

https://www.geeksforgeeks.org/modify-binary-tree-get-preorder-traversal-using-right-pointers/?ref=lbp 3/5
3/30/25, 10:25 PM Modify a binary tree to get preorder traversal using right pointers only | GeeksforGeeks
333

Output

10 8 3 5 2

[Expected Approach – 2] Using Iterative Preorder Traversal –


O(n) Time and O(n) Space

This can be easily done using Iterative preorder traversal. The


idea is to maintain a variable prev which maintains the previous
node of the preorder traversal. Every-time a new node is
encountered, the node set its right to previous one and prev is
made equal to the current node. In the end we will have a sort
of linked list whose first element is root then left child then right,
so on and so forth.

Below is the implementation of the above approach:

C++ Java Python C# JavaScript

// JavaScript code to modify binary tree


// for traversal using only right pointer

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

// An iterative process to set the right


// pointer of Binary tree
function modifytree(root) {

if (root === null) return;

// Create an empty stack and push


// root to it
const nodeStack = [];
nodeStack.push(root);

let pre = null;


while (nodeStack.length > 0) {

// Pop the top item from stack


const node = nodeStack.pop();

https://www.geeksforgeeks.org/modify-binary-tree-get-preorder-traversal-using-right-pointers/?ref=lbp 4/5
3/30/25, 10:25 PM Modify a binary tree to get preorder traversal using right pointers only | GeeksforGeeks
334
// Push right and left children of
// the popped node to stack
if (node.right !== null) nodeStack.push(node.right);
if (node.left !== null) nodeStack.push(node.left);

// Check if some previous node exists


if (pre !== null) {
pre.right = node;
}
pre = node;
}
}

function printpre(root) {
while (root !== null) {
console.log(root.data + " ");
root = root.right;
}
}

const 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);

modifytree(root);
printpre(root);

Output

10 8 3 5 2

https://www.geeksforgeeks.org/modify-binary-tree-get-preorder-traversal-using-right-pointers/?ref=lbp 5/5
3/30/25, 10:26 PM Construct Full Binary Tree using its Preorder traversal and Preorder traversal of its mirror tree | GeeksforGeeks
335

Construct Full Binary Tree using its Preorder


traversal and Preorder traversal of its mirror tree
Last Updated : 29 Oct, 2024

Given two arrays that represent Preorder traversals of a full binary


tree and its mirror tree, the task is to construct the binary tree using
these two Preorder traversals. A Full Binary Tree is a binary tree
where every node has either 0 or 2 children.

Note: It is not possible to construct a general binary tree using these


two traversals. But we can create a full binary tree using the above
traversals without any ambiguity. For more details refer to this article.

Examples:

Input: pre[] = [1, 2, 4, 5, 3, 6, 7]


preMirror[] = [1, 3, 7, 6, 2, 5, 4]

Output:

Approach:

https://www.geeksforgeeks.org/construct-full-binary-tree-using-preorder-traversal-preorder-traversal-mirror-tree/?ref=lbp 1/4
3/30/25, 10:26 PM Construct Full Binary Tree using its Preorder traversal and Preorder traversal of its mirror tree | GeeksforGeeks
336
The idea is to recursively creates the root node from pre[], then
searches for the next element in preM[] to split the subarrays for
constructing the left and right subtrees. Inorder traversal is
used to print the constructed tree.

Below is the implementation of above approach:

C++ Java Python C# JavaScript

// JavaScript program to construct full binary tree


// using its preorder traversal and preorder
// traversal of its mirror tree

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

// A recursive function to construct a full binary tree


// from pre[] and preM[]. preIndex is used to keep
// track of index in pre[]. l is low index and h is high
// index for the current subarray in preM[].
function constructBinaryTreeUtil(pre, preM, preIndex, l, h,
size) {
if (preIndex[0] >= size || l > h)
return null;

// Create the root node using the


// current preIndex
let root = new Node(pre[preIndex[0]]);
preIndex[0]++;

// If the current subarray has only one


// element, no need to recurse
if (l === h)
return root;

// Search the next element of pre[]


// in preM[]
let i = 0;
for (i = l; i <= h; ++i)
if (pre[preIndex[0]] === preM[i])
break;

// Recursively construct left and


// right subtrees
if (i <= h) {
root.left = constructBinaryTreeUtil(
pre, preM, preIndex, i, h, size);
root.right = constructBinaryTreeUtil(
pre, preM, preIndex, l + 1, i - 1, size);
}
https://www.geeksforgeeks.org/construct-full-binary-tree-using-preorder-traversal-preorder-traversal-mirror-tree/?ref=lbp 2/4
3/30/25, 10:26 PM Construct Full Binary Tree using its Preorder traversal and Preorder traversal of its mirror tree | GeeksforGeeks
337
return root;
}

// Function to construct the full binary tree using


// its preorder traversal and preorder traversal of its
// mirror tree.
function constructBinaryTree(pre, preMirror) {

let preIndex =
[ 0 ];
let size = pre.length;
return constructBinaryTreeUtil(pre, preMirror, preIndex,
0, size - 1, size);
}

function printInorder(curr) {
if (curr === null)
return;

printInorder(curr.left);
console.log(curr.data + " ");
printInorder(curr.right);
}

let preOrder = [ 1, 2, 4, 5, 3, 6, 7 ];
let preOrderMirror = [ 1, 3, 7, 6, 2, 5, 4 ];

let root = constructBinaryTree


(preOrder, preOrderMirror);

printInorder(root);

Output

4 2 5 1 6 3 7

Time Complexity: O(n^2), where n is number of nodes in tree.


Auxiliary Space: O(n)

If we observe carefully, then the reverse of the Preorder traversal of


the mirror tree will be the Postorder traversal of the original tree. We
can construct the tree from given Preorder and Postorder traversals in
a similar manner as above. You can refer to Construct Full Binary Tree
from given preorder and postorder traversals article on how to
Construct a Full Binary Tree from given preorder and postorder
traversals.

https://www.geeksforgeeks.org/construct-full-binary-tree-using-preorder-traversal-preorder-traversal-mirror-tree/?ref=lbp 3/4
3/30/25, 10:26 PM Construct Full Binary Tree using its Preorder traversal and Preorder traversal of its mirror tree | GeeksforGeeks
338

https://www.geeksforgeeks.org/construct-full-binary-tree-using-preorder-traversal-preorder-traversal-mirror-tree/?ref=lbp 4/4
3/30/25, 10:26 PM Construct a special tree from given preorder traversal | GeeksforGeeks
339

Construct a special tree from given preorder


traversal
Last Updated : 17 Oct, 2024

Given an array pre[] that represents the Preorder traversal of a


special binary tree where every node has either 0 or 2 children. One
more array preLN[] is given which has only two possible values ‘L’ and
‘N’. The value ‘L’ in preLN[] indicates that the corresponding node in
Binary Tree is a leaf node and the value ‘N’ indicates that the
corresponding node is a non-leaf node. The task is to construct the
tree from the given two arrays.

Example:

Input: pre[] = {10, 30, 20, 5, 15}, preLN[] = {‘N’, ‘N’, ‘L’, ‘L’, ‘L’}
Output:

Table of Content
[Expected Approach] Using Pre-Order Traversal – O(n) Time and
O(h) Space

https://www.geeksforgeeks.org/construct-a-special-tree-from-given-preorder-traversal/?ref=lbp 1/5
3/30/25, 10:26 PM Construct a special tree from given preorder traversal | GeeksforGeeks
340
[Alternate Approach] Using Stack – O(n) Time and O(h) Space

[Expected Approach] Using Pre-Order Traversal – O(n) Time


and O(h) Space

The first element in pre[] will always be root. So we can easily


figure out the root. If the left subtree is empty, the right subtree
must also be empty, and the preLN[] entry for root must be ‘L’.
We can simply create a node and return it. If the left and right
subtrees are not empty, then recursively call for left and right
subtrees and link the returned nodes to root.

C++ Java Python C# JavaScript

// JavaScript program to construct tree


// from preorder traversal

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

// Recursive function to construct the tree


function constructTreeRecur(index, pre, preLN) {

let root = new Node(pre[index[0]++]);

// If the current node is leaf node,


// then return the node.
if (preLN[index[0] - 1] === 'L') return root;

// Recursively create the left and right subtree.


root.left = constructTreeRecur(index, pre, preLN);
root.right = constructTreeRecur(index, pre, preLN);

return root;
}

function constructTree(n, pre, preLN) {

// base case
if (n === 0) return null;

let index = [0];


return constructTreeRecur(index, pre, preLN);
}

https://www.geeksforgeeks.org/construct-a-special-tree-from-given-preorder-traversal/?ref=lbp 2/5
3/30/25, 10:26 PM Construct a special tree from given preorder traversal | GeeksforGeeks
341
function inorder(root) {
if (root === null) return;
inorder(root.left);
console.log(root.data + " ");
inorder(root.right);
}

let pre = [10, 30, 20, 5, 15];


let preLN = ['N', 'N', 'L', 'L', 'L'];

let root = constructTree(pre.length, pre, preLN);


inorder(root);

Output

20 30 5 10 15

[Alternate Approach] Using Stack – O(n) Time and O(h) Space

The idea is to use a stack to implement pre-order traversal and


construct the binary tree and return the root node.

Step by step implementation:

1. As the Pre-order Traversal is given, so we first create the root node


and insert it into an empty stack.
2. Traverse the given pre-order traversal.
1. Create the node corresponding to the current value.
2. Check the top node in the stack:
If left of top node is null, then set the current node as left of
top node.
Else, right of top node is null, then set the current node as
right of top node and pop the top node.

3. If the present node is not a leaf node, push node into the stack.

3. Return the root of the constructed tree.

C++ Java Python C# JavaScript

https://www.geeksforgeeks.org/construct-a-special-tree-from-given-preorder-traversal/?ref=lbp 3/5
3/30/25, 10:26 PM Construct a special tree from given preorder traversal | GeeksforGeeks
342
// JavaScript program to construct tree
// from preorder traversal

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

// function to construct the tree


function constructTree(n, pre, preLN) {

// base case
if (n === 0) return null;

let st = [];

let root = new Node(pre[0]);

// Checking if root is not leaf node


if (preLN[0] !== 'L')
st.push(root);

// Iterating over the given node values


for (let i = 1; i < n; i++) {
let curr = new Node(pre[i]);

// Checking if the left position is


// NULL or not
if (!st[st.length - 1].left) {
st[st.length - 1].left = curr;
}

// Checking if the right position is


// NULL or not
else if (!st[st.length - 1].right) {
st[st.length - 1].right = curr;
st.pop();
}

// If current node is internal node,


// then push it to stack.
if (preLN[i] !== 'L')
st.push(curr);
}

return root;
}

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

const pre = [10, 30, 20, 5, 15];


https://www.geeksforgeeks.org/construct-a-special-tree-from-given-preorder-traversal/?ref=lbp 4/5
3/30/25, 10:26 PM Construct a special tree from given preorder traversal | GeeksforGeeks
343
const preLN = ['N', 'N', 'L', 'L', 'L'];
const n = pre.length;

const root = constructTree(n, pre, preLN);


inorder(root);

Output

20 30 5 10 15

Related article:

Construct the full k-ary tree from its preorder traversal

https://www.geeksforgeeks.org/construct-a-special-tree-from-given-preorder-traversal/?ref=lbp 5/5
3/30/25, 10:46 PM Construct Binary Tree from String with bracket representation | GeeksforGeeks
344

Construct Binary Tree from String with bracket


representation
Last Updated : 08 Feb, 2025

Given a string consisting of parenthesis and integers, representing a


binary tree. The task is to construct a binary tree from this string.

The string contains an integer followed by zero, one or two pairs of


parenthesis. The integer represents the root’s value and a pair of
parenthesis contains a child binary tree with the same structure.
Always start to construct the left child node of the parent first if it
exists.

Examples:

Input : “1(2)(3)”
Output : 1 2 3
Explanation :
1
/\
2 3

Input : “4(2(3)(1))(6(5))”
Output : 4 2 3 1 6 5
Explanation :
4
/ \
2 6
/\ /
3 15

Idea:

In a binary tree string representation, each part begins with a


number representing the node’s value, followed by at most two

https://www.geeksforgeeks.org/construct-binary-tree-string-bracket-representation/?ref=lbp 1/5
3/30/25, 10:46 PM Construct Binary Tree from String with bracket representation | GeeksforGeeks
345
pairs of parentheses. The first pair of parentheses after a number
contains the complete left subtree of that node (if it exists), and
the second pair of parentheses contains the complete right
subtree (if it exists). Each subtree follows the same pattern
recursively, making it a self-similar structure.

Table of Content
[Naive Approach] Using Recursion – O(n^2) time and O(n) space:
[Expected Approach] Using Pre-Order Traversal – O(n) time and
O(n) space

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


space:

The idea is to recursively parse the string by first extracting the


root value (which could be multiple digits) and then finding
matching pairs of parentheses that enclose the left and right
subtrees.

For each subtree enclosed in parentheses, we find its


corresponding closing parenthesis using a counter (incrementing
for ‘(‘ and decrementing for ‘)’), which helps us identify the
correct substring for the left child.

Once we have the left subtree’s closing index, we can process


the right subtree starting two positions after (to skip the closing
parenthesis and opening parenthesis of right subtree).

https://www.geeksforgeeks.org/construct-binary-tree-string-bracket-representation/?ref=lbp 2/5
3/30/25, 10:46 PM Construct Binary Tree from String with bracket representation | GeeksforGeeks
346
This process continues recursively until we either encounter an
empty substring (base case) or process all characters, effectively
building the tree from root to leaves.

C++ Java Python C# JavaScript

▸ {...}

// function to return the index of close parenthesis


function findIndex(str, i, j) {
if (i > j)
return -1;

let cnt = 0;

for (let k = i; k <= j; k++) {


if (str[k] === '(') cnt++;
else if (str[k] === ')') {
cnt--;

if (cnt === 0) return k;


}
}

return -1;
}

// function to construct tree from string


function constructTreeRecur(str, i, j) {

if (i > j) return null;

let val = 0;

while (i <= j && !isNaN(str[i])) {


val = val * 10 + (str[i] - '0');
i++;
}

let root = new Node(val);


let index = -1;

if (i <= j && str[i] === '(')


index = findIndex(str, i, j);

if (index !== -1) {


root.left = constructTreeRecur(str, i + 1, index - 1);
root.right = constructTreeRecur(str, index + 2, j - 1);
}

return root;
}

function treeFromString(str) {

https://www.geeksforgeeks.org/construct-binary-tree-string-bracket-representation/?ref=lbp 3/5
3/30/25, 10:46 PM Construct Binary Tree from String with bracket representation | GeeksforGeeks
347
return constructTreeRecur(str, 0, str.length - 1);
}

▸ {...}

Output

4 2 6 3 1 5 N N N N N N N

[Expected Approach] Using Pre-Order Traversal – O(n) time


and O(n) space

The idea is to traverse the string sequentially using a single


index passed by reference, constructing the tree in a preorder
manner (root-left-right) where we first extract the root value by
parsing consecutive digits, then recursively build the left subtree
if we encounter an opening parenthesis, and finally build the
right subtree if another opening parenthesis exists after
completing the left subtree construction.

Step by step approach:

1. Maintain a single index that traverses through the string from left to
right.
2. When encountering digits, parse them to form the complete node
value and create a new node with the parsed value.
3. If an opening parenthesis ‘(‘ is found, increment index and
recursively build left subtree. After left subtree is built and index is
incremented past closing parenthesis, check for another opening
parenthesis.
4. If second opening parenthesis exists, increment index and
recursively build right subtree.
5. Return the constructed node which serves as root for its subtree

C++ Java Python C# JavaScript

▸ {...}

https://www.geeksforgeeks.org/construct-binary-tree-string-bracket-representation/?ref=lbp 4/5
3/30/25, 10:46 PM Construct Binary Tree from String with bracket representation | GeeksforGeeks
348
function preOrder(i, s) {
if (s[i[0]] === ')') return null;

let val = 0;
while (i[0] < s.length && s[i[0]] !== '(' && s[i[0]] !== ')') {
let digit = s[i[0]] - '0';
i[0]++;
val = val * 10 + digit;
}

let root = new Node(val);

if (i[0] < s.length && s[i[0]] === '(') {


i[0]++;
root.left = preOrder(i, s);
i[0]++;
}

if (i[0] < s.length && s[i[0]] === '(') {


i[0]++;
root.right = preOrder(i, s);
i[0]++;
}

return root;
}

function treeFromString(s) {
let i = [0];
return preOrder(i, s);
}

▸ {...}

Output

4 2 6 3 1 5 N N N N N N N

https://www.geeksforgeeks.org/construct-binary-tree-string-bracket-representation/?ref=lbp 5/5
3/30/25, 10:46 PM Convert a Binary Tree into Doubly Linked List in spiral fashion | GeeksforGeeks
349

Convert a Binary Tree into Doubly Linked List in


spiral fashion
Last Updated : 30 Sep, 2024

Given a binary tree, convert it into a doubly linked list (DLL) where
the nodes are arranged in a spiral order. The left pointer of the binary
tree node should act as the previous node in the DLL, and the right
pointer should act as the next node in the DLL.

The solution should not allocate extra memory for the DLL nodes. It
should use the existing binary tree nodes for creating the DLL,
meaning only changes to the pointers are allowed.

Example:

Input:

Output:

https://www.geeksforgeeks.org/convert-a-binary-tree-into-doubly-linked-list-in-spiral-fashion/?ref=lbp 1/4
3/30/25, 10:46 PM Convert a Binary Tree into Doubly Linked List in spiral fashion | GeeksforGeeks
350
Explanation: The above binary tree is converted into doubly
linked list where left pointer of the binary tree node act as the
previous node and right pointer of the binary tree node act as the
next node.

Approach:

The idea is to use a deque (double-ended queue) that can be


expanded or contracted from both ends (either from its front or
its back). We perform a level-order traversal, but to maintain
spiral order, for every odd level, we dequeue a node from the
front and insert its left and right children at the back of the
deque. For each even level, we dequeue a node from the back
and insert its right and left children at the front of the deque.

We also maintain a stack to store the binary tree nodes.


Whenever we pop nodes from the deque, we push that node
into the stack. Later, we pop all the nodes from the stack and
insert them at the beginning of the list.

Below is the implementation of the above approach:

C++ Java Python C# JavaScript

// JavaScript program to convert Binary Tree into Doubly


// Linked List where the nodes are represented spirally

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

// Function to insert node at the


// front of DLL and return the new head
function push(head, node) {
node.right = head;
node.left = null;
if (head !== null) {
head.left = node;
}
return node;
}

// Function to perform spiral level-order traversal


// and convert binary tree into DLL

https://www.geeksforgeeks.org/convert-a-binary-tree-into-doubly-linked-list-in-spiral-fashion/?ref=lbp 2/4
3/30/25, 10:46 PM Convert a Binary Tree into Doubly Linked List in spiral fashion | GeeksforGeeks
351
function spiralToDLL(root) {
if (root === null) return null;

let dq = [];
dq.push(root);

let stk = [];


let head = null;
let leftToRight = true;

// Perform spiral level order traversal


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

while (levelSize--) {
if (leftToRight) {

// Left-to-right traversal: pop from front


let node = dq.shift();

// Push children for next level (left to right)


if (node.left !== null) dq.push(node.left);
if (node.right !== null) dq.push(node.right);

stk.push(node);
} else {

// Right-to-left traversal: pop from back


let node = dq.pop();

// Push children for next level (right to left)


if (node.right !== null) dq.unshift(node.right);
if (node.left !== null) dq.unshift(node.left);

stk.push(node);
}
}
leftToRight = !leftToRight;
}

// Pop nodes from stack and form the DLL


while (stk.length > 0) {
let node = stk.pop();

// Insert node at the front of DLL and update head


head = push(head, node);
}

// Return the head of the created DLL


return head;
}

function printList(node) {
while (node !== null) {
console.log(node.data);
node = node.right;
}
}

https://www.geeksforgeeks.org/convert-a-binary-tree-into-doubly-linked-list-in-spiral-fashion/?ref=lbp 3/4
3/30/25, 10:46 PM Convert a Binary Tree into Doubly Linked List in spiral fashion | GeeksforGeeks
352
// Example tree:
// 1
// / \
// 2 3
// / \ / \
// 4 5 6 7
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);
root.right.left = new Node(6);
root.right.right = new Node(7);

let head = spiralToDLL(root);


printList(head);

Output

1 3 2 4 5 6 7

Time Complexity: O(n), as we are using a loop to traverse n times.


Auxiliary Space: O(n), as we are using extra space for dequeue and
stack.

Related articles:

Convert a given Binary Tree to a Doubly Linked List | Set 1


Convert a given Binary Tree to a Doubly Linked List | Set 2
Convert a given Binary Tree to a Doubly Linked List | Set 3
Convert a given Binary Tree to a Doubly Linked List | Set 4
Convert a given Binary Tree to a Doubly Linked List | Set 5

https://www.geeksforgeeks.org/convert-a-binary-tree-into-doubly-linked-list-in-spiral-fashion/?ref=lbp 4/4
3/30/25, 10:46 PM Convert a Binary Tree to a Circular Doubly Link List | GeeksforGeeks
353

Convert a Binary Tree to a Circular Doubly Link


List
Last Updated : 10 Jan, 2023

Given a Binary Tree, convert it to a Circular Doubly Linked List (In-


Place).

The left and right pointers in nodes are to be used as previous and
next pointers respectively in the converted Circular Linked List.
The order of nodes in the List must be the same as in Inorder for the
given Binary Tree.
The first node of Inorder traversal must be the head node of the
Circular List.

Examples:

Convert a Binary Tree to a Circular Doubly Link List


using Recursion:

The idea is to make a general-purpose function that


concatenates two given circular doubly lists
https://www.geeksforgeeks.org/convert-a-binary-tree-to-a-circular-doubly-link-list/?ref=lbp 1/7
3/30/25, 10:46 PM Convert a Binary Tree to a Circular Doubly Link List | GeeksforGeeks
354

Follow the steps below to solve the problem:

Recursively convert the left subtree to a circular DLL. Let the


converted list be leftList.
Recursively convert the right subtree to a circular DLL. Let the
converted list be rightList.
Make a circular linked list of roots of the tree, and make the left and
right root points to themselves.
Concatenate leftList with the list of the single root node.
Concatenate the list produced in the step above with rightList.

Note: The above approach traverses the tree in a Postorder fashion.


We can traverse in an inorder fashion also. We can first concatenate
left subtree and root, then recur for the right subtree and concatenate
the result with left-root concatenation.

How do Concatenate two circular DLLs?

Get the last node of the left list. Retrieving the last node is an O(1)
operation since the prev pointer of the head points to the last node
of the list.
Connect it with the first node of the right list
Get the last node of the second list
Connect it with the head of the list.

Below are implementations of the above idea:

// javascript Program to convert a Binary Tree to a


// Circular Doubly Linked List

// Node class represents a Node of a Tree


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

https://www.geeksforgeeks.org/convert-a-binary-tree-to-a-circular-doubly-link-list/?ref=lbp 2/7
3/30/25, 10:46 PM Convert a Binary Tree to a Circular Doubly Link List | GeeksforGeeks
355
// A class to represent a

var root = null;

// concatenate both the lists and returns the head


// of the List
function concatenate(leftList, rightList) {
// If either of the list is empty, then
// return the other list
if (leftList == null)
return rightList;
if (rightList == null)
return leftList;

// Store the last Node of left List


var leftLast = leftList.left;

// Store the last Node of right List


var rightLast = rightList.left;

// Connect the last node of Left List


// with the first Node of the right List
leftLast.right = rightList;
rightList.left = leftLast;

// left of first node refers to


// the last node in the list
leftList.left = rightLast;

// Right of last node refers to the first


// node of the List
rightLast.right = leftList;

// Return the Head of the List


return leftList;
}

// Method converts a to a circular


// Link List and then returns the head
// of the Link List
function bTreeToCList(root) {
if (root == null)
return null;

// Recursively convert left and right subtrees


var left = bTreeToCList(root.left);
var right = bTreeToCList(root.right);

https://www.geeksforgeeks.org/convert-a-binary-tree-to-a-circular-doubly-link-list/?ref=lbp 3/7
3/30/25, 10:46 PM Convert a Binary Tree to a Circular Doubly Link List | GeeksforGeeks
356
// Make a circular linked list of single node
// (or root). To do so, make the right and
// left pointers of this node point to itself
root.left = root.right = root;

// Step 1 (concatenate the left list with the list


// with single node, i.e., current node)
// Step 2 (concatenate the returned list with the
// right List)
return concatenate(concatenate(left, root), right);
}

// Display Circular Link List


function display(head) {
document.write("Circular Linked List is :<br/>");
var itr = head;
do {
document.write(itr.val + " ");
itr = itr.right;
} while (itr != head);
document.write();
}

// Driver Code

// Build the
root = new Node(10);
root.left = new Node(12);
root.right = new Node(15);
root.left.left = new Node(25);
root.left.right = new Node(30);
root.right.left = new Node(36);

// head refers to the head of the Link List


var head = bTreeToCList(root);

// Display the Circular LinkedList


display(head);

// This code contributed by umadevi9616

Output

Circular Linked List is :

https://www.geeksforgeeks.org/convert-a-binary-tree-to-a-circular-doubly-link-list/?ref=lbp 4/7
3/30/25, 10:46 PM Convert a Binary Tree to a Circular Doubly Link List | GeeksforGeeks
357
25 12 30 10 36 15

Time Complexity: O(N), As every node is visited at most once.


Auxiliary space: O(log N), The extra space is used in the recursion call
stack which can grow up to a maximum size of logN as it is a binary
tree.

Convert a Binary Tree to a Circular Doubly Link List


by Inorder Traversal:

The idea is to do in-order traversal of the binary tree. While


doing inorder traversal, keep track of the previously visited node
in a variable, say prev. For every visited node, make it the next of
the prev and set previous of this node as prev.

Follow the steps below to solve the problem:

First convert the binary tree into doubly linked list refer to this post
Convert a given Binary Tree to Doubly Linked List.
Now convert this Doubly Linked List to circular Doubly linked list by
connecting first and last node.

Below is the implementation of the above approach.

// A javascript program for in-place conversion of Binary Tree to DLL


// A binary tree node has data, left pointers and right pointers
class Node {
constructor(val) {
this.data = val;
this.left = null;
this.right = null;
}
}
var root;

// head --> Pointer to head node of created doubly linked list


var head;

// Initialize previously visited node as NULL. This is


// so that the same value is accessible in all recursive
// calls

https://www.geeksforgeeks.org/convert-a-binary-tree-to-a-circular-doubly-link-list/?ref=lbp 5/7
3/30/25, 10:46 PM Convert a Binary Tree to a Circular Doubly Link List | GeeksforGeeks
358
var prev = null;

// A simple recursive function to convert a given Binary tree


// to Doubly Linked List
// root --> Root of Binary Tree
function BinaryTree2DoubleLinkedList(root)
{

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

// Recursively convert left subtree


BinaryTree2DoubleLinkedList(root.left);

// Now convert this node


if (prev == null)
head = root;
else {
root.left = prev;
prev.right = root;
}
prev = root;

// Finally convert right subtree


BinaryTree2DoubleLinkedList(root.right);
}

/* Function to print nodes in a given doubly linked list */


function printList(node) {
while (node != null) {
console.log(node.data + " ");
node = node.right;
}
}

// Driver program to test above functions


// Let us create the tree as shown in above diagram
root = new Node(10);
root.left = new Node(12);
root.right = new Node(15);
root.left.left = new Node(25);
root.left.right = new Node(30);
root.right.left = new Node(36);

// convert to DLL
BinaryTree2DoubleLinkedList(root);

// Print the converted List

https://www.geeksforgeeks.org/convert-a-binary-tree-to-a-circular-doubly-link-list/?ref=lbp 6/7
3/30/25, 10:46 PM Convert a Binary Tree to a Circular Doubly Link List | GeeksforGeeks
359
printList(head);

// This code is contributed by ishankhandelwals.

Output

25 12 30 10 36 15

Time Complexity: O(N), As every node is visited at most once.


Auxiliary space: O(log N), The extra space is used in the recursive
function call stack which can grow upto a maximum size of logN.

This approach was contributed by Abhijeet Kumar

https://www.geeksforgeeks.org/convert-a-binary-tree-to-a-circular-doubly-link-list/?ref=lbp 7/7
3/30/25, 10:46 PM Convert Ternary Expression to a Binary Tree | GeeksforGeeks
360

Convert Ternary Expression to a Binary Tree


Last Updated : 14 Sep, 2023

Given a string that contains ternary expressions. The expressions may


be nested, task is convert the given ternary expression to a binary
Tree.

Examples:

Input : string expression = a?b:c


Output : a
/ \
b c
Input : expression = a?b?c:d:e
Output : a
/ \
b e
/ \
c d

Asked In : Facebook Interview

Idea is that we traverse a string make first character as root and


do following step recursively .

1. If we see Symbol ‘?’


then we add next character as the left child of root.

2. If we see Symbol ‘:’


then we add it as the right child of current root.

https://www.geeksforgeeks.org/convert-ternary-expression-binary-tree/?ref=lbp 1/5
3/30/25, 10:46 PM Convert Ternary Expression to a Binary Tree | GeeksforGeeks
361

do this process until we traverse all element of “String”.

Below is the implementation of above idea

// Javascript program to convert a ternary


// expreesion to a tree.

// Class to represent Tree node


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

// Function to convert Ternary Expression


// to a Binary Tree. It return the root of tree
function convertExpression(expression, i)
{

// Base case
if (i >= expression.length)
{
return null;
}

// Store current character of


// expression_string [ 'a' to 'z']
var root = new Node(expression[i]);

// Move ahead in str


++i;

// If current character of ternary expression


// is '?' then we add next character as a
// left child of current node
if (i < expression.length && expression[i] == '?')
{
https://www.geeksforgeeks.org/convert-ternary-expression-binary-tree/?ref=lbp 2/5
3/30/25, 10:46 PM Convert Ternary Expression to a Binary Tree | GeeksforGeeks
362
root.left = convertExpression(expression, i + 1);
}

// Else we have to add it as a right child


// of current node expression.at(0) == ':'
else if (i < expression.length)
{
root.right = convertExpression(expression, i + 1);
}
return root;
}

// Function print tree


function printTree(root)
{
if (root == null)
{
return;
}
document.write(root.data + " ");
printTree(root.left);
printTree(root.right);
}

// Driver code
var exp = "a?b?c:d:e";
var expression = exp.split('');
var root = convertExpression(expression, 0);
printTree(root);

// This code is contributed by noob2000

Output

a b c d e

Time Complexity : O(n) [ here n is length of String ]


Auxiliary Space: O(n)

Approach for Converting Ternary Expression to Binary Tree.

https://www.geeksforgeeks.org/convert-ternary-expression-binary-tree/?ref=lbp 3/5
3/30/25, 10:46 PM Convert Ternary Expression to a Binary Tree | GeeksforGeeks
363
The algorithm uses a recursive approach to build the tree in a top-
down manner.
It starts with creating a new node for the current character at the
current index.
If the next character is a ‘?’, it means that the current node needs a
left child. So, the algorithm calls itself recursively with the next
index to create the left child of the current node.
If the next character is a ‘:’, it means that the current node needs a
right child. So, the algorithm calls itself recursively with the next
index to create the right child of the current node.
Finally, the algorithm returns the root node of the binary tree.

Here is the implementation of above approach:-

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

let i = 0;

function convertExpression(expression) {
if (!expression || i >= expression.length) {
return null;
}

const root = new Node(expression[i]);


i++;

if (i < expression.length && expression[i] === "?") {


i++;
root.left = convertExpression(expression);
}

if (i < expression.length && expression[i] === ":") {


i++;
root.right = convertExpression(expression);
}

return root;
}
https://www.geeksforgeeks.org/convert-ternary-expression-binary-tree/?ref=lbp 4/5
3/30/25, 10:46 PM Convert Ternary Expression to a Binary Tree | GeeksforGeeks
364

function printTree(root) {
if (!root) {
return;
}

console.log(root.val + " ");


printTree(root.left);
printTree(root.right);
}

const stringExpression = "a?b?c:d:e";


const rootNode = convertExpression(stringExpression);
printTree(rootNode);

Output

a b c d e

Time complexity: O(n) – Since we visit each character of the


expression exactly once.

Space complexity: O(n) – Since in the worst case, the recursion stack
can grow to the height of the tree, which can be O(n) if the ternary
expression is a degenerate tree (a long chain of ‘?’). Additionally, we
store O(n) nodes in the binary tree.

https://www.geeksforgeeks.org/convert-ternary-expression-binary-tree/?ref=lbp 5/5
3/30/25, 10:47 PM Check if there is a root to leaf path with given sequence | GeeksforGeeks
365

Check if there is a root to leaf path with given


sequence
Last Updated : 11 Oct, 2024

Given a binary tree and an array, the task is to find if the given array
sequence is present as a root-to-leaf path in given tree.

Examples:

Input: arr = {5, 2, 4, 8}

Output: True
Explanation: The given array sequence {5, 2, 4, 8} is present as a
root-to-leaf path in given tree.

Input: arr = {5, 3, 4, 9}

https://www.geeksforgeeks.org/check-root-leaf-path-given-sequence/?ref=lbp 1/4
3/30/25, 10:47 PM Check if there is a root to leaf path with given sequence | GeeksforGeeks
366

Output: False
Explanation: The given array sequence {5, 3, 4, 9} is not present
as a root-to-leaf path in given tree.

A simple solution for this problem is to find all root-to-leaf paths in


given tree and for each root-to-leaf path check whether path and
given sequence in array both are identical or not.

Approach:

The idea is to traverse the tree once and while traversing the tree
we have to check if path from root to current node is identical
to the given sequence of root to leaf path.

Algorithm:

Start traversing tree in preorder fashion.


Whenever we moves down in tree then we also move by one index
in given sequence of root to leaf path .
If current node is equal to the arr[index] this means that till this
level of tree path is identical.
Now remaining path will either be in left subtree or in right
subtree.
If any node gets mismatched with arr[index] this means that
current path is not identical to the given sequence of root to leaf
path, so we return back and move in right subtree.

https://www.geeksforgeeks.org/check-root-leaf-path-given-sequence/?ref=lbp 2/4
3/30/25, 10:47 PM Check if there is a root to leaf path with given sequence | GeeksforGeeks
367
Now when we are at leaf node and it is equal to arr[index] and
there is no further element in given sequence of root to leaf path,
this means that path exist in given tree.

Below is the implementation of the above approach:

C++ Java Python C# JavaScript

// JavaScript code to check if the given array sequence


// exists as a root-to-leaf path in a binary tree
class Node {
constructor(x) {
this.data = x;
this.left = null;
this.right = null;
}
}

// Function to check if the path exists


function checkPath(root, arr, index) {

// If root is null or index exceeds


// array size, return false
if (!root || index >= arr.length) {
return false;
}

// If current node does not match the


// array element, return false
if (root.data !== arr[index]) {
return false;
}

// If we reach the leaf node and


// the sequence matches fully
if (!root.left && !root.right &&
index === arr.length - 1) {
return true;
}

// Recurse for left and right subtrees


// by moving to next index in arr
return checkPath(root.left, arr, index + 1) ||
checkPath(root.right, arr, index + 1);
}

// Representation of the given tree


// 5
// / \
// 2 3
// / \
// 1 4
// / \
// 6 8

https://www.geeksforgeeks.org/check-root-leaf-path-given-sequence/?ref=lbp 3/4
3/30/25, 10:47 PM Check if there is a root to leaf path with given sequence | GeeksforGeeks
368
const root = new Node(5);
root.left = new Node(2);
root.right = new Node(3);
root.left.left = new Node(1);
root.left.right = new Node(4);
root.left.right.left = new Node(6);
root.left.right.right = new Node(8);

const arr = [5, 2, 4, 8];

if (checkPath(root, arr, 0)) {


console.log("True");
} else {
console.log("False");
}

Output

True

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


Auxiliary Space: O(h), due to the recursive call stack, where h is the
height of the tree.

https://www.geeksforgeeks.org/check-root-leaf-path-given-sequence/?ref=lbp 4/4
3/30/25, 10:47 PM Remove all nodes which lie on a path having sum less than k | GeeksforGeeks
369

Remove all nodes which lie on a path having sum


less than k
Last Updated : 19 Oct, 2024

Given a binary tree, a complete path is defined as a path from a root


to a leaf. The sum of all nodes on that path is defined as the sum of
that path. Given the number k, the task is to remove all nodes that lie
on a path with a sum less than k.

Note: A node can be part of multiple paths. So we have to delete it


only in case when all paths from it have a sum less than k.

Input: k= 20

Output:

https://www.geeksforgeeks.org/remove-all-nodes-which-lie-on-a-path-having-sum-less-than-k/?ref=lbp 1/4
3/30/25, 10:47 PM Remove all nodes which lie on a path having sum less than k | GeeksforGeeks
370

Explanation: Nodes with values 8 and 6 are deleted because the


path sum from root to node with value 8 is 15 and the path sum
from root to node with value 6 is 10.

Approach:

The idea is to traverse the binary tree recursively. At each node,


decrement the required sum of the path. At the end of paths,
check if the sum is less than equal to 0. If it is yes, then return
true (meaning this path has sum >= k). Else return false. For the
nodes, if false is returned by left and right subtree, then delete
the current node and return false. If false is returned by only one
subtree, then set the corresponding pointer to null. Then return
true.

Below is the implementation of the above approach:

C++ C Java Python C# JavaScript

// JavaScript program to Remove all nodes which


// don’t lie in any path with sum>= k

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

https://www.geeksforgeeks.org/remove-all-nodes-which-lie-on-a-path-having-sum-less-than-k/?ref=lbp 2/4
3/30/25, 10:47 PM Remove all nodes which lie on a path having sum less than k | GeeksforGeeks
371
// Function to prune the tree
function pruneTree(root, k) {
if (root === null) return k <= 0;

let left = pruneTree(root.left, k - root.data);


let right = pruneTree(root.right, k - root.data);

if (!left && !right) {


return false;
} else if (!left) {
root.left = null;
} else if (!right) {
root.right = null;
}

return true;
}

function inOrder(root) {
if (root === null) return;

inOrder(root.left);
console.log(root.data);
inOrder(root.right);
}

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

let k = 7;
pruneTree(root, k);
inOrder(root);

Output

2 5 1

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


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

https://www.geeksforgeeks.org/remove-all-nodes-which-lie-on-a-path-having-sum-less-than-k/?ref=lbp 3/4
3/30/25, 10:47 PM Remove all nodes which lie on a path having sum less than k | GeeksforGeeks
372

https://www.geeksforgeeks.org/remove-all-nodes-which-lie-on-a-path-having-sum-less-than-k/?ref=lbp 4/4
3/30/25, 10:47 PM Maximum spiral sum in Binary Tree | GeeksforGeeks
373

Maximum spiral sum in Binary Tree


Last Updated : 22 Oct, 2024

Given a binary tree containing n nodes. The task is to find the


maximum sum obtained when the tree is spirally traversed. In spiral
traversal one by one all levels are being traversed with the root level
traversed from right to left, then the next level from left to right, then
further next level from right to left and so on.

Example:

Input:

Output: 7
Explanation: Maximum spiral sum = 4 + (-1) + (-2) + 1 + 5 = 7

https://www.geeksforgeeks.org/maximum-spiral-sum-in-binary-tree/?ref=lbp 1/4
3/30/25, 10:47 PM Maximum spiral sum in Binary Tree | GeeksforGeeks
374

Approach:

The idea is to obtain the level order traversal in spiral form of the
given binary tree with the help of two stacks and store it in an
array. Find the maximum sum sub-array of the array so obtained.

Below is the implementation of the above approach:

C++ Java Python C# JavaScript

// JavaScript program to maximum


// spiral sum in Binary Tree

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

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

let currentLevel = [];


let nextLevel = [];
currentLevel.push(root);

// variable to indicate direction


// of traversal.
let leftToRight = false;

// Array to store spiral traversal.


let arr = [];

https://www.geeksforgeeks.org/maximum-spiral-sum-in-binary-tree/?ref=lbp 2/4
3/30/25, 10:47 PM Maximum spiral sum in Binary Tree | GeeksforGeeks
375
while (currentLevel.length > 0) {
let size = currentLevel.length;
while (size-- > 0) {
let curr = currentLevel.pop();
arr.push(curr.data);

// if current direction to lor, then


// push left node first, so that next
// level traversal is rol.
if (leftToRight) {
if (curr.left !== null)
nextLevel.push(curr.left);
if (curr.right !== null)
nextLevel.push(curr.right);
} else {
if (curr.right !== null)
nextLevel.push(curr.right);
if (curr.left !== null)
nextLevel.push(curr.left);
}
}

// Flip the direction.


leftToRight = !leftToRight;

// Swap the arrays.


let temp = currentLevel;
currentLevel = nextLevel;
nextLevel = temp;
}

let ans = Number.MIN_SAFE_INTEGER;

// variable to store the sum of


// current subarray.
let prev = 0;

// Performing kadane's algorithm


for (let i = 0; i < arr.length; i++) {

// If the current subarray sum is less than


// 0, then start a new subarray from
// index i.
if (prev < 0) prev = 0;

// include the current value into


// the subarray sum.
prev += arr[i];

// Compare the current subarray sum


// with the maximum subarray sum.
ans = Math.max(ans, prev);
}

return ans;
}

// Binary tree
// -2

https://www.geeksforgeeks.org/maximum-spiral-sum-in-binary-tree/?ref=lbp 3/4
3/30/25, 10:47 PM Maximum spiral sum in Binary Tree | GeeksforGeeks
376
// / \
// -3 4
// / \ / \
// 5 1 -2 -1
// / \
// -3 2
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(1);
root.right.left = new Node(-2);
root.right.right = new Node(-1);
root.left.left.left = new Node(-3);
root.right.right.right = new Node(2);

console.log(spiralSum(root));

Output

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


Auxiliary Space: O(n).

https://www.geeksforgeeks.org/maximum-spiral-sum-in-binary-tree/?ref=lbp 4/4
3/30/25, 10:47 PM Sum of nodes at k-th level in a tree represented as string | GeeksforGeeks
377

Sum of nodes at k-th level in a tree represented as


string
Last Updated : 14 Oct, 2024

Given an integer k and a binary tree in string format. Every node of a


tree has a value in the range of 0 to 9. The task is to find the sum of
elements at the k-th level from the root. The root is at level 0.
Tree is given in the form: (node value(left subtree)(right subtree))

Examples:

Input : s = “(0(5(6()())(4()(9()())))(7(1()())(3()())))” , k = 2
Output : 14
Explanation: The tree representation is shown below:

Elements at level k = 2 are 6, 4, 1, 3 and the sum of the digits of


these elements = 6 + 4 + 1 + 3 = 14

Table of Content
[Naive Approach] Using Pre-order traversal – O(n) Time and O(h)
Space

https://www.geeksforgeeks.org/sum-nodes-k-th-level-tree-represented-string/?ref=lbp 1/4
3/30/25, 10:47 PM Sum of nodes at k-th level in a tree represented as string | GeeksforGeeks
378
[Expected Approach] Using Iterative Method – O(n) Time and O(1)
Space

[Naive Approach] Using Pre-order traversal – O(n) Time and


O(h) Space

The idea is to treat the string as tree without actually creating


one, and simply traverse the string recursively in pre-order
manner and consider nodes that are at level k only.

Note: This approach may give Stack Overflow error.

Below is the implementation of the above approach:

C++ Java Python C# JavaScript

// JavaScript implementation to find sum of


// digits of elements at k-th level

function kLevelSumRecur(i, s, k, level) {

if (s[i[0]] === '(') i[0]++;

// Find the value of current node.


let val = 0;
while (i[0] < s.length && s[i[0]] !== '(' && s[i[0]] !== ')') {
val = val * 10 + (s.charCodeAt(i[0]) - '0'.charCodeAt(0));
i[0]++;
}

// Append the value of current node


// only if it is at level k.
val = (level === k) ? val : 0;

let left = 0, right = 0;

// If left subtree exists


if (i[0] < s.length && s[i[0]] === '(') {
left = kLevelSumRecur(i, s, k, level + 1);
}

// if right subtree exists


if (i[0] < s.length && s[i[0]] === '(') {
right = kLevelSumRecur(i, s, k, level + 1);
}

// To take care of closing parenthesis


i[0]++;

return val + left + right;

https://www.geeksforgeeks.org/sum-nodes-k-th-level-tree-represented-string/?ref=lbp 2/4
3/30/25, 10:47 PM Sum of nodes at k-th level in a tree represented as string | GeeksforGeeks
379
}

// Function to find sum of digits


// of elements at k-th level
function kLevelSum(s, k) {
let i = [0];
return kLevelSumRecur(i, s, k, 0);
}

const s = "(0(5(6()())(4()(9()())))(7(1()())(3()())))";
const k = 2;
console.log(kLevelSum(s, k));

Output

14

[Expected Approach] Using Iterative Method – O(n) Time and


O(1) Space

The idea is to iterate over the string and use the brackets to find
the level of the current node. If current character is ‘(‘, then
increment the level. If current character is ‘)’, then decrement
the level.

Step by step approach:

1. Initialize two variables,say level = -1 and sum = 0


2. for each character ‘ch’ in ‘s’
if ch == ‘(‘ then increment the level.
else if ch == ‘)’ then decrement the level.
else if level == k, then add the node value to sum.

3. return sum.

Below is the implementation of the above approach:

C++ Java Python C# JavaScript

// JavaScript implementation to find sum of


// digits of elements at k-th level

// Function to find sum of digits

https://www.geeksforgeeks.org/sum-nodes-k-th-level-tree-represented-string/?ref=lbp 3/4
3/30/25, 10:47 PM Sum of nodes at k-th level in a tree represented as string | GeeksforGeeks
380
// of elements at k-th level
function kLevelSum(s, k) {
let level = -1;
let sum = 0;
let n = s.length;

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

// increasing level number


if (s[i] === '(')
level++;

// decreasing level number


else if (s[i] === ')')
level--;

// check if current level is


// the desired level or not
else if (level === k) {
let val = 0;

// find the value of node


while (i < n && s[i] !== '(' && s[i] !== ')') {
val = val * 10 + (s.charCodeAt(i) - '0'.charCodeAt(0));
i++;
}
i--;
sum += val;
}
}

return sum;
}

const s = "(0(5(6()())(4()(9()())))(7(1()())(3()())))";
const k = 2;
console.log(kLevelSum(s, k));

Output

14

https://www.geeksforgeeks.org/sum-nodes-k-th-level-tree-represented-string/?ref=lbp 4/4
3/30/25, 10:47 PM Sum of all the numbers that are formed from root to leaf paths | GeeksforGeeks
381

Sum of all the numbers that are formed from root


to leaf paths
Last Updated : 04 Nov, 2024

Given a binary tree, where every node value is a number. Find the
sum of all the numbers that are formed from root to leaf paths.

Examples:

Input:

Output: 13997
Explanation: There are 4 leaves, hence 4 root to leaf paths:

6->3->2 = 632
6->3->5->7 = 6357
6->3->5->4 = 6354
6->5->4 = 654

final answer = 632 + 6357 + 6354 + 654 = 13997

Input:

https://www.geeksforgeeks.org/sum-numbers-formed-root-leaf-paths/?ref=lbp 1/6
3/30/25, 10:47 PM Sum of all the numbers that are formed from root to leaf paths | GeeksforGeeks
382

Output: 2630
Explanation: There are 3 leaves, resulting in leaf path of 1240,
1260, 130 sums to 2630.

The Naive approach to solve this problem is to first find all the paths
from the root to the leaf . Then we convert all paths into numbers. In
the end, we will add those numbers. Time Complexity of this approach
will be O(n^2) because we are traversing the all the paths and space
will be O(n).

Table of Content
[Expected Approach] Using Pre-order traversal – O(n) Time and
O(h) Space
[Alternate Approach] Using Iterative Method – O(n) Time and O(h)
Space

[Expected Approach] Using Pre-order traversal – O(n) Time


and O(h) Space

The idea is to do a preorder traversal of the tree. In the preorder


traversal, keep track of the value calculated till the current node.
For every node, we update the value as value*10 plus the node’s
data. On reaching a leaf node, return the value calculated so far.

https://www.geeksforgeeks.org/sum-numbers-formed-root-leaf-paths/?ref=lbp 2/6
3/30/25, 10:47 PM Sum of all the numbers that are formed from root to leaf paths | GeeksforGeeks
383
C++ C Java Python C# JavaScript

// JavaScript program to find sum of


// all paths from root to leaves
class Node {
constructor(x) {
this.data = x;
this.left = null;
this.right = null;
}
}

// Function which returns the sum of root to leaf path.


function treePathsSum(root, val = 0) {
if (root === null) return 0;

// Update value
val = val * 10 + root.data;

// If node is leaf node, then


// return the value.
if (root.left === null && root.right === null)
return val;

return treePathsSum(root.left, val)


+ treePathsSum(root.right, val);
}

// Hard coded binary tree.


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

console.log(treePathsSum(root));

Output

13997

[Alternate Approach] Using Iterative Method – O(n) Time and


O(h) Space
https://www.geeksforgeeks.org/sum-numbers-formed-root-leaf-paths/?ref=lbp 3/6
3/30/25, 10:47 PM Sum of all the numbers that are formed from root to leaf paths | GeeksforGeeks
384
The idea behind the Iterative Depth-First Search (DFS) using a
Stack approach is to traverse the binary tree iteratively in a
depth-first manner while keeping track of the path sum from the
root to the current node. We use a stack to store pairs of nodes
and their corresponding path sums.

Step by step approach:

Start with an initial sum value of 0 and create an empty stack.


Push the root node onto the stack along with its value as the initial
path sum.
While the stack is not empty, do the following:
Pop a node and its corresponding path sum from the stack.
If the popped node is a leaf (i.e., it has no left and right
children), add the path sum to the overall result.
If the popped node has a right child, push the right child
onto the stack with the updated path sum. The updated
path sum is obtained by multiplying the current path sum
by 10 and adding the value of the right child.
If the popped node has a left child, push the left child onto
the stack with the updated path sum. The updated path
sum is obtained by multiplying the current path sum by 10
and adding the value of the left child.
Once the stack is empty, return the overall result, which represents
the sum of all the numbers formed from root to leaf paths.

Below is the implementation of the above approach:

C++ Java Python C# JavaScript

// JavaScript program to find sum of


// all paths from root to leaves

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

https://www.geeksforgeeks.org/sum-numbers-formed-root-leaf-paths/?ref=lbp 4/6
3/30/25, 10:47 PM Sum of all the numbers that are formed from root to leaf paths | GeeksforGeeks
385
// Function which returns the sum of root to leaf path.
function treePathsSum(root) {

// base case
if (root === null) return 0;

// Store pair of node and value


// associated with it.
let st = [[root, 0]];

let ans = 0;

while (st.length > 0) {


let [curr, val] = st.pop();

// update the value


val = val * 10 + curr.data;

// if current node is leaf node,


// then add the value to result.
if (curr.left === null && curr.right === null) {
ans += val;
continue;
}

if (curr.right !== null) {


st.push([curr.right, val]);
}

if (curr.left !== null) {


st.push([curr.left, val]);
}
}

return ans;
}

// Hard coded binary tree.


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

console.log(treePathsSum(root));

Output
https://www.geeksforgeeks.org/sum-numbers-formed-root-leaf-paths/?ref=lbp 5/6
3/30/25, 10:47 PM Sum of all the numbers that are formed from root to leaf paths | GeeksforGeeks
386
13997

https://www.geeksforgeeks.org/sum-numbers-formed-root-leaf-paths/?ref=lbp 6/6
3/30/25, 10:48 PM Merge Two Binary Trees by doing Node Sum | GeeksforGeeks
387

Merge Two Binary Trees by doing Node Sum


Last Updated : 16 Dec, 2024

Given the roots of two binary trees. The task is to merge the two
trees. The merge rule is that if two nodes overlap, then sum node
values up as the new value of the merged node. Otherwise, the non-
null node will be used as the node of the new tree.

Note: The merging process must start from the root nodes of both
trees.

Examples:

Input:

Output:

https://www.geeksforgeeks.org/merge-two-binary-trees-node-sum/?ref=lbp 1/7
3/30/25, 10:48 PM Merge Two Binary Trees by doing Node Sum | GeeksforGeeks
388

Explanation: root of the both the trees overlap, they sum up to


give 2.

Input:

Output:

https://www.geeksforgeeks.org/merge-two-binary-trees-node-sum/?ref=lbp 2/7
3/30/25, 10:48 PM Merge Two Binary Trees by doing Node Sum | GeeksforGeeks
389

Table of Content
Using Recursion – O(n) Time and O(h) Space
Using Iteration – O(n) Time and O(n) Space

Using Recursion – O(n) Time and O(h) Space

The idea is to traverse both the given trees in preorder fashion.


At each step, check whether the current node exists (NOT null)
for both of the trees. If so, add the values and update in the first
tree, else return the non-null node(if it exists). Now recursively
apply this operation for left and right subtree. At the end, the
first tree will represent the merged binary tree.

C++ C Java Python C# JavaScript

// Javascript program to Merge Two Binary Trees


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

// Function to print the inorder traversal of the tree.


function inorder(node) {

if (node === null)


return;

https://www.geeksforgeeks.org/merge-two-binary-trees-node-sum/?ref=lbp 3/7
3/30/25, 10:48 PM Merge Two Binary Trees by doing Node Sum | GeeksforGeeks
390
// Recur on left child
inorder(node.left);

// Print the value of the current node


console.log(node.data);

// Recur on right child


inorder(node.right);
}

// Function to merge two binary trees


function mergeTrees(t1, t2) {

// If either of the nodes is null, return the other node


if (t1 === null)
return t2;
if (t2 === null)
return t1;

// If both nodes are not null, add the value of t2's


// node to t1's node
t1.data += t2.data;

// Recursively merge left and right children


t1.left = mergeTrees(t1.left, t2.left);
t1.right = mergeTrees(t1.right, t2.right);

// Return the merged tree


return t1;
}

// construct the first Binary Tree


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

let root1 = new Node(1);


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

// construct the second Binary Tree


//
// 4
// / \
// 1 7
// / / \
// 3 2 6

let root2 = new Node(4);


root2.left = new Node(1);
root2.right = new Node(7);
root2.left.left = new Node(3);

https://www.geeksforgeeks.org/merge-two-binary-trees-node-sum/?ref=lbp 4/7
3/30/25, 10:48 PM Merge Two Binary Trees by doing Node Sum | GeeksforGeeks
391
root2.right.left = new Node(2);
root2.right.right = new Node(6);

let root = mergeTrees(root1, root2);


inorder(root);

Output

7 3 5 5 2 10 12

Using Iteration – O(n) Time and O(n) Space

The idea is to traverse both the given trees using a stack. At


each step, check whether the current nodes exist (not NULL) for
both of the trees. If so, add the values and update in the first
tree. Otherwise, if the left child of the first tree exists, push the
left children (pair) of both trees onto the stack. If not, append
the left child of the second tree to the current node of the first
tree. Repeat the same process for the right child pair. If both the
current nodes are null, continue with the next node pair from the
stack. At the end, the first tree will represent the merged binary
tree.

C++ Java Python C# JavaScript

// Javascript program to Merge Two Binary Trees


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

// Function to perform inorder traversal of the binary tree


function inorder(node) {

// Base case: if the node is null, return


if (node === null)
return;

// Recursively traverse the left subtree


inorder(node.left);

// Print the current node's data


console.log(node.data + " ");

// Recursively traverse the right subtree


https://www.geeksforgeeks.org/merge-two-binary-trees-node-sum/?ref=lbp 5/7
3/30/25, 10:48 PM Merge Two Binary Trees by doing Node Sum | GeeksforGeeks
392
inorder(node.right);
}

// Function to merge two binary trees iteratively using a


// stack
function mergeTrees(t1, t2) {

// If the first tree is null, return the second tree


if (t1 === null)
return t2;

// If the second tree is null, return the first tree


if (t2 === null)
return t1;

// Stack to store pairs of nodes to be processed


let stack = [];

// Push the root nodes of both trees into the stack


stack.push({tree1 : t1, tree2 : t2});

while (stack.length > 0) {

// Get the top pair of nodes from the stack


let {tree1, tree2} = stack.pop();

// If either node is null, skip this pair


if (tree1 === null || tree2 === null)
continue;

// Add the data of the second tree's node to the


// first tree's node
tree1.data += tree2.data;

// If the left child of tree1 is null, assign it to


// tree2's left child
if (tree1.left === null)
tree1.left = tree2.left;
else
stack.push(
{tree1 : tree1.left, tree2 : tree2.left});

// If the right child of tree1 is null, assign it to


// tree2's right child
if (tree1.right === null)
tree1.right = tree2.right;
else
stack.push(
{tree1 : tree1.right, tree2 : tree2.right});
}

return t1;
}

// Construct the first Binary Tree


// 1
// / \
// 2 3

https://www.geeksforgeeks.org/merge-two-binary-trees-node-sum/?ref=lbp 6/7
3/30/25, 10:48 PM Merge Two Binary Trees by doing Node Sum | GeeksforGeeks
393
// / \ \
// 4 5 6

const root1 = new Node(1);


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

// Construct the second Binary Tree


// 4
// / \
// 1 7
// / / \
// 3 2 6

const root2 = new Node(4);


root2.left = new Node(1);
root2.right = new Node(7);
root2.left.left = new Node(3);
root2.right.left = new Node(2);
root2.right.right = new Node(6);

const mergedRoot = mergeTrees(root1, root2);


inorder(mergedRoot);

Output

7 3 5 5 2 10 12

https://www.geeksforgeeks.org/merge-two-binary-trees-node-sum/?ref=lbp 7/7
3/30/25, 10:48 PM Find the Root of a Tree from the Sum of Child Node IDs | GeeksforGeeks
394

Find the Root of a Tree from the Sum of Child


Node IDs
Last Updated : 12 Dec, 2024

Given a Binary Tree with nodes labelled from 1 to n, where n is the


total number of nodes. The task is to identify the root of binary tree
given that each node is described by a pair consisting of its id and the
sum of its children’s id’s.

Examples:

Input: [[1, 5], [2, 0], [3, 0], [4, 0], [5, 5], [6, 5]]
Output: 6
Explanation: In this question, two trees having 6 as their root
node can me generated.

Input: [[4, 0]
Output: 4
Explanation: 4 is the only node in a tree and thus does not have
any child as well.

https://www.geeksforgeeks.org/find-root-tree-children-id-sum-every-node-given/?ref=lbp 1/3
3/30/25, 10:48 PM Find the Root of a Tree from the Sum of Child Node IDs | GeeksforGeeks
395
Approach:

The idea is to use the property that every node id, except for the
root, appears in the sum of children ids. By calculating the total
sum of all node id’s and subtracting it to the total sum of all
children sum, the difference will be the id of the root node.

C++ Java Python C# JavaScript

// JavaScript to Find root of tree where


// children sum for every node id is given.

function findRoot(arr) {

// Subtract the sum of children


// from the sum of all nodes
let root = 0;
for (let i = 0; i < arr.length; i++) {

// Add the node Id to the root


root += arr[i][0];

// Subtract the sum of children


root -= arr[i][1];
}

// Return the root of the tree


return root;
}

let arr = [
[ 1, 5 ], [ 2, 0 ], [ 3, 0 ], [ 4, 0 ], [ 5, 5 ],
[ 6, 5 ]
];

// The given array represents the following binary tree


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

console.log(findRoot(arr));

Output

https://www.geeksforgeeks.org/find-root-tree-children-id-sum-every-node-given/?ref=lbp 2/3
3/30/25, 10:48 PM Find the Root of a Tree from the Sum of Child Node IDs | GeeksforGeeks
396
Time Complexity: O(n), Where n is the length of the given array.
Auxiliary Space: O(1), As no extra space is used.

https://www.geeksforgeeks.org/find-root-tree-children-id-sum-every-node-given/?ref=lbp 3/3

You might also like