Tree
Tree
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
class Node
{
constructor(item)
{
this.data = item;
this.left = this.right = null;
}
}
https://www.geeksforgeeks.org/introduction-to-binary-tree/?ref=lbp 2/17
3/30/25, 4:07 PM Introduction to Binary Tree | GeeksforGeeks
3
class Node {
constructor(d) {
this.data = d;
this.left = null;
this.right = null;
}
}
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
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:
// Node structure
class Node {
constructor(data) {
this.data = data;
this.left = null;
this.right = null;
}
}
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);
}
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
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.
class Node {
constructor(d) {
this.data = d;
this.left = null;
this.right = null;
}
}
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 key = 6;
root = insert(root, key);
Output
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.
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;
}
}
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
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.
class Node {
constructor(d) {
this.data = d;
this.left = null;
this.right = null;
}
}
// In-order traversal
function inorder(root) {
if (root === null) return;
inorder(root.left);
console.log(root.data + " ");
inorder(root.right);
}
let valToDel = 3;
root = deleteNode(root, valToDel);
Output
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
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.
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.
https://www.geeksforgeeks.org/introduction-to-binary-tree/?ref=lbp 14/17
3/30/25, 4:07 PM Introduction to Binary Tree | GeeksforGeeks
15
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.
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:
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
Level Definition: The number of edges in the path from the root to
a node. The root is at level 0.
Proof by Induction:
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
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”
1 + 2 + 4 +…+ 2h = 2h+1 – 1
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 ≥ ⌊log2N⌋
This means a binary tree with N nodes must have at least ⌊log2N⌋
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 = ⌊log2L⌋
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:
Simplifies to L=T+1
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.
Node Relationships
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.
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):
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
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
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.
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
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/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
4 min read
4 min read
2 min read
2 min read
7 min read
2 min read
5 min read
4 min read
2 min read
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
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
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]
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
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:
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:
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:
function root(key) {
if (tree[0] != null) {
console.log("Tree already had root");
} else {
tree[0] = 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();
Output
ABCDE-F---
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
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
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.
▸ {...}
▸ {...}
Output
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
▸ {...}
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
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.
▸ {...}
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
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
Approach:
class Node {
constructor(x) {
this.data = x;
this.left = null;
this.right = null;
}
}
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
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!
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…
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
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
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
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
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]
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
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
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
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
class Node {
constructor(data) {
this.data = data;
this.left = null;
this.right = null;
}
}
https://www.geeksforgeeks.org/deletion-binary-tree/?ref=lbp 4/6
3/30/25, 4:09 PM Deletion in a Binary Tree | GeeksforGeeks
54
}
}
if (curr.left) queue.push(curr.left);
if (curr.right) queue.push(curr.right);
}
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;
}
Output
7 8 12 10 15 9
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
https://www.geeksforgeeks.org/enumeration-of-binary-trees/?ref=lbp 1/8
3/30/25, 4:09 PM Enumeration of Binary Trees | GeeksforGeeks
57
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.
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.
Therefore,
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
5 min read
10 min read
8 min read
9 min read
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…
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
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
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]
https://www.geeksforgeeks.org/enumeration-of-binary-trees/?ref=lbp 8/8
3/30/25, 4:09 PM Types of Binary Tree | GeeksforGeeks
64
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
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.
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.
A complete binary tree is just like a full binary tree, but with two major
differences:
https://www.geeksforgeeks.org/types-of-binary-tree/?ref=lbp 3/10
3/30/25, 4:09 PM Types of Binary Tree | GeeksforGeeks
67
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.
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
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.
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.
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.
2. AVL Tree
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
4. B – Tree
6. Segment 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
https://www.geeksforgeeks.org/types-of-binary-tree/?ref=lbp 10/10
3/30/25, 4:10 PM Complete Binary Tree | GeeksforGeeks
74
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.
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
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;
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.
Example 1:
A 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:
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.
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
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
Algorithm:
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.
Illustration:
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
https://www.geeksforgeeks.org/complete-binary-tree/?ref=lbp 7/9
3/30/25, 4:10 PM Complete Binary Tree | GeeksforGeeks
81
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
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.
In other words, it can be said that each level of the tree is completely
filled by the nodes.
https://www.geeksforgeeks.org/perfect-binary-tree/?ref=lbp 1/4
3/30/25, 4:10 PM Perfect Binary Tree | GeeksforGeeks
84
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.
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
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
Level Order Traversal visits all nodes at a lower level before moving to
a higher level. It can be implemented using:
Recursion
Queue (Iterative)
class Node {
constructor(value) {
this.data = value;
this.left = null;
this.right = null;
}
}
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
Output
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
class Node {
constructor(value) {
this.data = value;
this.left = null;
this.right = null;
}
}
// Enqueue Root
q.push(root);
let currLevel = 0;
// 5
// / \
// 12 13
// / \ \
// 7 14 2
// / \ / \ / \
//17 23 27 3 8 11
Output
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
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
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.
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
<script>
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;
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
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
<script>
// Javascript implementation of an O(n) approach of
// level order traversal in spiral form
let root;
function printSpiral(node)
{
if (node == null) {
return; // NULL check
}
if (temp.left != null) {
s2.push(temp.left);
}
}
Output
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.
The idea is to use Doubly Ended Queues, then push and pop the
nodes from each end in alternate order.
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
let root;
function printSpiral(node)
{
if (node == null) {
return; // NULL check
}
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);
}
}
Output
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
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:
class Node {
constructor(x) {
this.data = x;
this.left = null;
this.right = null;
}
}
reverseLevelOrder(root);
Output
4 5 2 3 1
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:
class Node {
constructor(x) {
this.data = x;
this.left = null;
this.right = null;
}
}
// Dequeue node
let curr = Q.shift();
S.push(curr);
// 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);
}
}
reverseLevelOrder(root);
Output
4 5 2 3 1
function reverseLevelOrder(root) {
const result = [];
const map = new Map();
return result;
}
function printList(list) {
console.log(list.join(" "));
}
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
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
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.
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):
Stands for BFS stands for Breadth DFS stands for Depth First
First Search. Search.
Conceptual BFS builds the tree DFS builds the tree sub-tree
Difference level by level. by sub-tree.
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
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:
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.
class Node {
constructor(x) {
this.data = x;
this.left = this.right = null;
}
}
function preOrder(root) {
while (root) {
preOrder(root);
console.log();
Output
1 2 4 5 3 6 7
Limitations:
https://www.geeksforgeeks.org/morris-traversal-for-preorder/?ref=lbp 4/4
3/30/25, 4:12 PM Iterative Preorder Traversal | GeeksforGeeks
118
The right child is pushed before the left child to make sure that
the left subtree is processed first.
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;
}
}
// Base Case
if (node == null)
{
return;
}
// 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
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.
class Node
{
constructor(item)
{
this.left = null;
this.right = null;
this.data = item;
}
}
let root;
https://www.geeksforgeeks.org/iterative-preorder-traversal/?ref=lbp 3/7
3/30/25, 4:12 PM Iterative Preorder Traversal | GeeksforGeeks
121
let st = [];
if (curr.right != null)
st.push(curr.right);
curr = curr.left;
}
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();
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:
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:
class Node {
constructor(item) {
this.data = item;
this.left = this.right = null;
}
}
class BinaryTree {
constructor() {
this.root = null;
}
morrisTraversalPreorder() {
this.morrisTraversalPreorderHelper(this.root);
}
preorder() {
this.preorderHelper(this.root);
}
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
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
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:
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
Following are the steps to print Postorder traversal of the above tree
using two stacks:
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
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
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
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.
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();
return ans;
}
Output
4 5 2 3 1
Realted articles:
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
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.
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.
class Node {
constructor(x) {
this.key = x;
this.left = null;
this.right = null;
}
}
// Base case
if (root === null)
return;
let level = 0;
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
}
Output
8 10 14 3 6 7 13 1 4
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
Given a binary tree, the task is to find the boundary nodes of the
binary tree Anti-Clockwise starting from the root.
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
▸ {...}
function isLeaf(node) {
return !node.left && !node.right;
}
res.push(root.data);
if (root.left) {
collectBoundaryLeft(root.left, res);
} else if (root.right) {
collectBoundaryLeft(root.right, res);
}
}
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);
}
if (root.right) {
collectBoundaryRight(root.right, res);
} else if (root.left) {
collectBoundaryRight(root.left, res);
}
res.push(root.data);
}
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
▸ {...}
}
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;
}
}
}
}
res.push(...temp.reverse());
}
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
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:
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);
function findDepth(tree) {
Output
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
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
class Node {
constructor(key) {
this.key = key;
this.left = null;
this.right = null;
}
}
return root;
}
function printInorder(head) {
if (!head) {
return;
}
printInorder(head.left);
console.log(head.key);
printInorder(head.right);
}
Output
4 8 10 12 14 20 22
Related articles:
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
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
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.
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;
}
}
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)
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.
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.
class Node {
constructor(x) {
this.data = x;
this.left = null;
this.right = null;
}
}
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 (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)
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.
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.
class Node {
constructor(x) {
this.data = x;
this.left = null;
this.right = null;
}
}
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);
Output
True
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
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
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.
// JavaScript program to
// check if two Nodes are Cousins
class Node {
constructor(x) {
this.data = x;
this.left = this.right = null;
}
}
return isSibling(root.left, a, b) ||
isSibling(root.right, a, b);
}
// base cases
if (root == null)
return 0;
if (root.data === value)
return lev;
if (a === b)
return false;
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
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
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
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.
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;
}
}
// Base case
if (root === null) return false;
// 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
class Node {
constructor(x) {
this.data = x;
this.left = null;
this.right = null;
}
}
// Base case
if (root === null)
return 0;
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;
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
Given a Binary Tree, the task is to check whether the given Binary Tree
is a perfect Binary Tree or not.
Note:
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
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.
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;
}
}
return 1 + Math.max(depth(root.left),
depth(root.right));
}
function isPerfect(root) {
// 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
class Node {
constructor(x) {
this.data = x;
this.left = null;
this.right = null;
}
}
function isPerfect(root) {
let q = [];
q.push(root);
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();
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
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
class Node {
constructor(x) {
this.data = x;
this.left = null;
this.right = null;
}
}
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";
return curr;
}
function dupSub(root) {
let 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
class Node {
constructor(data) {
this.data = data;
this.left = null;
this.right = null;
}
}
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');
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
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:
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
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.
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
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
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
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.
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;
}
if (isFoldable(root)) {
console.log("True");
} else {
console.log("False");
}
Output
True
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.
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 (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.
class Node {
constructor(x) {
this.data = x;
this.left = null;
this.right = null;
}
}
let q = [];
q.push(root.left);
q.push(root.right);
while (q.length) {
let a = q.shift();
let b = q.shift();
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;
}
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
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
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;
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);
}
Output
true
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.
class Node {
constructor(val) {
this.data = val;
this.left = this.right = null;
}
}
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
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
Output
Yes
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.
if (isIdentical(r1, r2)) {
console.log("Yes");
}
else {
console.log("No");
}
Output
Yes
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.
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.
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;
}
if (isIdentical(r1, r2)) {
console.log("Yes");
}
else {
console.log("No");
}
Output
Yes
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
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
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;
}
}
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
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.
class Node {
constructor(x) {
this.val = x;
this.left = null;
this.right = null;
}
}
let sum = 0;
const stack = [root];
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
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
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
class Node {
constructor(x) {
this.data = x;
this.left = null;
this.right = null;
}
}
s.push('1');
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);
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
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) {
return root;
}
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];
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
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).
class Node {
constructor(x) {
this.data = x;
this.left = null;
this.right = null;
}
}
console.log(getSize(root));
Output
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
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
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.
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.
class Node {
constructor(x) {
this.data = x;
this.left = null;
this.right = null;
}
}
// 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
Related article:
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
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
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.
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
}
}
const target = 5;
console.log(getLevel(root, target, 1));
Output
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.
class Node {
constructor(val) {
this.data = val;
this.left = this.right = null;
}
}
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
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
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
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;
}
}
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;
}
Output
10 12 15 25 30 36
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
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:
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:
class Node {
constructor(data) {
this.data = data;
this.left = null;
this.right = null;
}
}
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;
}
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;
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
Related articles:
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
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;
}
}
Initially, all next pointers have NULL values. Your function should fill
these next pointers so that they point to inorder successor.
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;
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
Output
Next of 3 is 8
Next of 8 is 10
Next of 10 is 12
Next of 12 is -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
Examples:
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
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:
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 = [];
while (!visited[j]) {
visited[j] = true;
j = t[j][1];
cycleSize++;
}
Output
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
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:
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
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);
return head;
}
function printList(head) {
let curr = head;
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.
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.
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) {
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;
}
}
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 7/7
3/30/25, 10:22 PM Convert a tree to forest of even nodes | GeeksforGeeks
250
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:
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);
return num + 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
https://www.geeksforgeeks.org/convert-tree-forest-even-nodes/?ref=lbp 4/4
3/30/25, 10:22 PM Flip Binary Tree | GeeksforGeeks
254
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
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
root->left->left = root->right
root->left->right = root
root->left = NULL
root->right = NULL
class Node {
constructor(x) {
this.data = x;
this.left = null;
this.right = null;
}
}
return flippedRoot;
}
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);
Output
2
3 1
4 5
class Node {
constructor(x) {
this.data = x;
this.left = null;
this.right = null;
}
}
function flipBinaryTree(root) {
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) {
curr.right = prev;
prev = curr;
curr = next;
}
return prev;
}
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
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
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.
class Node {
constructor(data) {
this.data = data;
this.left = null;
this.right = null;
}
}
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();
}
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
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.
class Node {
constructor(x) {
this.data = x;
this.left = null;
this.right = null;
}
}
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;
}
allPaths.forEach(path => {
console.log(path.join(' '));
});
Output
10 8 3
10 8 5
10 2 2
Related article:
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
Examples:
Output: True
Explanation: All of the above three traversals are of the same
tree:
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
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;
}
return root;
}
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;
}
Output
True
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;
}
return root;
}
postIndex[0]++;
return true;
}
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 N = preorder.length;
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
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:
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
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
const q = [];
q.push(root);
let end = false;
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
}
return true;
}
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 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:
return true;
}
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
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
EDIT
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.
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
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>")
Output
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 :
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);
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);
}
}
Output
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
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);
}
}
}
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
Tree1: 1 4 2 3 5
Tree2: 1 4 2
Yes Tree2 is subroot of Tree1
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
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
console.log(findLargestSubtreeSum(root));
Output
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)
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) {
const n = q.length;
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));
return ans;
}
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
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
class Node {
constructor(x) {
this.data = x;
this.left = null;
this.right = null;
}
}
function getMaxSum(root) {
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);
}
console.log(getMaxSum(root));
Output
11
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.
class Node {
constructor(data) {
this.data = data;
this.left = null;
this.right = null;
}
}
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);
console.log(getMaxSum(root));
Output
11
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:
class Node {
constructor(x) {
this.data = x;
this.left = null;
this.right = null;
}
}
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);
}
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
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)
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
class Node {
constructor(x) {
this.data = x;
this.left = null;
this.right = null;
}
}
// base case
if (root === null)
return false;
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
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:
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.
class Node {
constructor(k) {
this.left = null;
this.right = null;
this.data = k;
}
}
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;
Output
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
class Node {
constructor(k) {
this.data = k;
this.left = null;
this.right = null;
}
}
if (!root)
return null;
// Base Case
if (root == null)
return false;
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);
Output
Related articles:
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
Examples:
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
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
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.
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
function buildTree(parent) {
let adj
= Array.from({length : parent.length}, () => []);
let root = -1;
// Increment level
q.push([ child, level + 1 ]);
}
}
}
return maxHeight;
}
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
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.
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.
// If root node
if (parent[node] === -1) {
function findHeight(parent) {
let n = parent.length;
return maxHeight;
}
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
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
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.
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;
if (root.data === a) {
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
}
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
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.
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;
}
}
if (root.data === k) {
return level;
}
return left;
}
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
}
console.log(findDistance(root, 4, 7));
Output
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.
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 8/9
3/30/25, 10:25 PM Find distance between two nodes of a Binary Tree | GeeksforGeeks
329
}
// 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
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
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
class Node {
constructor(data) {
this.data = data;
this.left = null;
this.right = null;
}
}
function printpre(curr) {
while (curr != null) {
console.log(curr.data + " ");
curr = curr.right;
}
}
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
class Node {
constructor(data) {
this.data = data;
this.left = null;
this.right = null;
}
}
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);
function printpre(root) {
while (root !== null) {
console.log(root.data + " ");
root = root.right;
}
}
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
Examples:
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.
class Node {
constructor(data) {
this.data = data;
this.left = this.right = null;
}
}
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 ];
printInorder(root);
Output
4 2 5 1 6 3 7
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
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
class Node {
constructor(x) {
this.data = x;
this.left = null;
this.right = null;
}
}
return root;
}
// base case
if (n === 0) return null;
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);
}
Output
20 30 5 10 15
3. If the present node is not a leaf node, push node into the stack.
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;
}
}
// base case
if (n === 0) return null;
let st = [];
return root;
}
function inorder(root) {
if (root === null) return;
inorder(root.left);
console.log(root.data + " ");
inorder(root.right);
}
Output
20 30 5 10 15
Related article:
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
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:
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
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.
▸ {...}
let cnt = 0;
return -1;
}
let val = 0;
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
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
▸ {...}
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;
}
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
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:
class Node {
constructor(data) {
this.data = data;
this.left = this.right = null;
}
}
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);
while (levelSize--) {
if (leftToRight) {
stk.push(node);
} else {
stk.push(node);
}
}
leftToRight = !leftToRight;
}
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);
Output
1 3 2 4 5 6 7
Related articles:
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
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:
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.
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
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;
// 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);
Output
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
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.
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;
// Base case
if (root == null)
return;
// convert to DLL
BinaryTree2DoubleLinkedList(root);
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);
Output
25 12 30 10 36 15
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
Examples:
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
// Base case
if (i >= expression.length)
{
return null;
}
// Driver code
var exp = "a?b?c:d:e";
var expression = exp.split('');
var root = convertExpression(expression, 0);
printTree(root);
Output
a b c d e
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.
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;
}
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;
}
Output
a b c d e
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
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:
Output: True
Explanation: The given array sequence {5, 2, 4, 8} is present as a
root-to-leaf path in given tree.
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.
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:
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.
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);
Output
True
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
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
Approach:
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;
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
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
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.
class Node {
constructor(x) {
this.data = x;
this.left = null;
this.right = null;
}
}
function spiralSum(root) {
if (root === null) return 0;
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);
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
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
Examples:
Input : s = “(0(5(6()())(4()(9()())))(7(1()())(3()())))” , k = 2
Output : 14
Explanation: The tree representation is shown below:
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
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
}
const s = "(0(5(6()())(4()(9()())))(7(1()())(3()())))";
const k = 2;
console.log(kLevelSum(s, k));
Output
14
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.
3. return sum.
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;
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
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
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
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
// Update value
val = val * 10 + root.data;
console.log(treePathsSum(root));
Output
13997
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;
let ans = 0;
return ans;
}
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
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
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
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);
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);
Output
7 3 5 5 2 10 12
return t1;
}
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
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
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.
function findRoot(arr) {
let arr = [
[ 1, 5 ], [ 2, 0 ], [ 3, 0 ], [ 4, 0 ], [ 5, 5 ],
[ 6, 5 ]
];
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