Ilovepdf Merged
Ilovepdf Merged
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
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
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
https://www.geeksforgeeks.org/introduction-to-binary-tree/?ref=lbp 5/17
3/30/25, 4:07 PM Introduction to Binary Tree | GeeksforGeeks
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
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
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
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
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
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
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
https://www.geeksforgeeks.org/introduction-to-binary-tree/?ref=lbp 14/17
3/30/25, 4:07 PM Introduction to Binary Tree | GeeksforGeeks
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
https://www.geeksforgeeks.org/introduction-to-binary-tree/?ref=lbp 17/17
3/30/25, 4:07 PM Properties of Binary Tree | GeeksforGeeks
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
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
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
Related Articles:
See Handshaking Lemma and Tree for proof
Different types of Binary Trees and their properties
Introduction to Binary Tree in set 1
https://www.geeksforgeeks.org/properties-of-binary-tree/?ref=lbp 5/5
3/30/25, 4:08 PM Applications, Advantages and Disadvantages of Binary Tree | GeeksforGeeks
38
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
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
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
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
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
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
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
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
/ \ \
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
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
Given a binary tree, the task is to find the maximum depth of the tree.
The maximum depth or height of the tree is the number of edges in
the tree from the root to the deepest node.
Examples:
Input:
Output: 2
Explanation: The longest path from the root (node 12) goes
through node 8 to node 5, which has 2 edges.
Input:
https://www.geeksforgeeks.org/find-the-maximum-depth-or-height-of-a-tree/?ref=lbp 1/7
3/30/25, 4:08 PM Maximum Depth of Binary Tree | GeeksforGeeks
Output: 3
Explanation: The longest path from the root (node 1) to a leaf
node 6 with 3 edge.
Table of Content
[Approach 1] Using Recursion – O(n) Time and O(h) Space
[Approach 2] Level Order Traversal using Null Delimiter – O(n)
Time and O(n) Space
[Approach 3] Level Order Traversal without using Null Delimiter –
O(n) Time and O(n) Space
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
▸ {...}
https://www.geeksforgeeks.org/find-the-maximum-depth-or-height-of-a-tree/?ref=lbp 5/7
3/30/25, 4:08 PM Maximum Depth of Binary Tree | GeeksforGeeks
▸ {...}
Output
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
// Increment depth after traversing a level
depth++;
}
return depth - 1;
}
▸ {...}
Output
https://www.geeksforgeeks.org/find-the-maximum-depth-or-height-of-a-tree/?ref=lbp 7/7
3/30/25, 4:08 PM Insertion in a Binary Tree in level order | GeeksforGeeks
38
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
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
// / \
// 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
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
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
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
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
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
Approach:
https://www.geeksforgeeks.org/deletion-binary-tree/?ref=lbp 3/6
3/30/25, 4:09 PM Deletion in a Binary Tree | GeeksforGeeks
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
}
}
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
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
38
https://www.geeksforgeeks.org/enumeration-of-binary-trees/?ref=lbp 1/8
3/30/25, 4:09 PM Enumeration of Binary Trees | GeeksforGeeks
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
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
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
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
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
https://www.geeksforgeeks.org/enumeration-of-binary-trees/?ref=lbp 8/8
3/30/25, 4:09 PM Types of Binary Tree | GeeksforGeeks
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
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
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
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
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
Binary Search Tree is a node-based binary tree data structure that has
the following properties:
The left subtree of a node contains only nodes with keys lesser than
the node’s key.
https://www.geeksforgeeks.org/types-of-binary-tree/?ref=lbp 6/10
3/30/25, 4:09 PM Types of Binary Tree | GeeksforGeeks
The right subtree of a node contains only nodes with keys greater
than the node’s key.
The left and right subtree each must also be a binary search tree.
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
AVL Tree
4. B – Tree
5. 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
Segment Tree
https://www.geeksforgeeks.org/types-of-binary-tree/?ref=lbp 10/10
3/30/25, 4:10 PM Complete Binary Tree | GeeksforGeeks
https://www.geeksforgeeks.org/complete-binary-tree/?ref=lbp 1/9
3/30/25, 4:10 PM Complete Binary Tree | GeeksforGeeks
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
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
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
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
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 1: Initialize the root with a new node when the tree is empty.
Step 2: If the tree is not empty then get the front element
If the front element does not have a left child then set the left child
to a new node
If the right child is not present set the right child as a new node
Step 3: If the node has both the children then pop it from the queue.
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
https://www.geeksforgeeks.org/complete-binary-tree/?ref=lbp 8/9
3/30/25, 4:10 PM Complete Binary Tree | GeeksforGeeks
https://www.geeksforgeeks.org/complete-binary-tree/?ref=lbp 9/9
3/30/25, 4:10 PM Perfect Binary Tree | GeeksforGeeks
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
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
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
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
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
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
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
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
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
<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
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
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
<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
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
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
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
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
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
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
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
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
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
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
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
Given a Binary Tree, the task is to print its Preorder Traversal, without
using recursion or stack.
Examples:
Input:
Output: 1 2 4 5 3
Explanation: Preorder traversal (Root->Left->Right) of the tree
is 1 2 4 5 3
Input:
https://www.geeksforgeeks.org/morris-traversal-for-preorder/?ref=lbp 1/4
3/30/25, 4:11 PM Morris traversal for Preorder | GeeksforGeeks
Output: 8 1 7 10 5 10 6 6
Explanation: Preorder traversal (Root->Left->Right) of the tree
is 8 1 7 10 5 10 6 6
Approach:
https://www.geeksforgeeks.org/morris-traversal-for-preorder/?ref=lbp 2/4
3/30/25, 4:11 PM Morris traversal for Preorder | GeeksforGeeks
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
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
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
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
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
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
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
Given a binary tree, the task is to find the postorder traversal of the
tree without using recursion.
Examples:
Input:
Output: 4 5 2 3 1
Explanation: Postorder traversal (Left->Right->Root) of the tree
is 4 5 2 3 1.
Input:
https://www.geeksforgeeks.org/iterative-postorder-traversal/?ref=lbp 1/6
3/30/25, 4:12 PM Iterative Postorder Traversal | Set 1 (Using Two Stacks) | GeeksforGeeks
Output: 10 7 1 6 10 6 5 8
Explanation: Postorder traversal (Left->Right->Root) of the tree
is 10 7 1 6 10 6 5 8 .
Approach:
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
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
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
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
https://www.geeksforgeeks.org/iterative-postorder-traversal/?ref=lbp 6/6
3/30/25, 4:12 PM Diagonal Traversal of Binary Tree | GeeksforGeeks
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
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
}
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
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
▸ {...}
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
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
▸ {...}
}
while (current) {
if (!current.left) {
// If it's a leaf node
if (!current.right)
res.push(current.data);
current = current.right;
}
else {
// Find the inorder predecessor
let predecessor = current.left;
while (predecessor.right && predecessor.right !== current) {
predecessor = predecessor.right;
}
https://www.geeksforgeeks.org/boundary-traversal-of-binary-tree/?ref=lbp 4/6
3/30/25, 4:12 PM Boundary Traversal of binary tree | GeeksforGeeks
if (!predecessor.right) {
predecessor.right = current;
current = current.left;
}
else {
// If it's predecessor is a leaf node
if (!predecessor.left)
res.push(predecessor.data);
predecessor.right = null;
current = current.right;
}
}
}
}
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
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
The given tree can be seen as a full binary tree where every node has
0 or two children. The two children of a node can be ‘n’ or a or a mix
of both.
Examples :
Input: s = “nlnll”
Output: 2
Explanation: Below is the representation of the tree formed from
the string with depth equals to 2.
Input: s = “nlnnlll”
https://www.geeksforgeeks.org/calculate-depth-full-binary-tree-preorder/?ref=lbp 1/3
3/30/25, 4:20 PM Calculate depth of a full Binary tree from Preorder | GeeksforGeeks
Output: 3
Explanation: Below is the representation of the tree formed from
the string with depth equals to 3.
Approach:
https://www.geeksforgeeks.org/calculate-depth-full-binary-tree-preorder/?ref=lbp 2/3
3/30/25, 4:20 PM Calculate depth of a full Binary tree from Preorder | GeeksforGeeks
let right = findDepthRec(tree, n, index);
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
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
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
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
Given a binary tree, the task is to check if it is a Sum Tree. A Sum Tree
is a Binary Tree where the value of a node is equal to the sum of the
nodes present in its left subtree and right subtree. An empty tree is
Sum Tree and the sum of an empty tree can be considered as 0. A leaf
node is also considered a Sum Tree.
Example:
Input:
Output: True
Explanation: The above tree follows the property of Sum Tree.
Input:
https://www.geeksforgeeks.org/check-if-a-given-binary-tree-is-sumtree/?ref=lbp 1/7
3/30/25, 4:24 PM Check if a given Binary Tree is Sum Tree | GeeksforGeeks
Output: False
Explanation: The above tree doesn’t follows the property of Sum
Tree as 6 + 2 != 10.
Table of Content
[Naive Approach] By Checking Every Node – O(n^2) Time and O(h)
Space
[Expected Approach] Calculating left and right subtree sum directly
– O(n) Time and O(h) Space
[Alternate Approach] Using post order traversal – O(n) Time and
O(h) Space
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
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
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
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
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
// 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
Given a binary tree (having distinct node values) root and two node
values. The task is to check whether the two nodes with values a and
b are cousins.
Note: Two nodes of a binary tree are cousins if they have the same
depth with different parents.
Example:
Input: a = 5, b = 4
Output: True
Explanation: Node with the values 5 and 4 are on the same level
with different parents.
Input: a = 4, b = 5
https://www.geeksforgeeks.org/check-two-nodes-cousins-binary-tree/?ref=lbp 1/5
3/30/25, 4:24 PM Check if two nodes are cousins in a Binary Tree | GeeksforGeeks
Output: False
Explanation: Node with the values 5 and 4 are on the same level
with same parent.
Table of Content
Using Depth First Search
Using Breadth-First Search
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;
}
}
// Base case
if (root == null)
return false;
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
// / \
// 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
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
Given a Binary Tree, the task is to find if there exists an edge whose
removal creates two trees of equal size.
Examples:
Input:
Output : True
Explanation: Removing edge 5-6 creates two trees of equal size.
Input:
https://www.geeksforgeeks.org/check-if-removing-an-edge-can-divide-a-binary-tree-in-two-halves/?ref=lbp 1/6
3/30/25, 4:24 PM Check if removing an edge can divide a Binary Tree in two halves | GeeksforGeeks
Output : False
Explanation: There is no edge whose removal creates two trees
of equal size.
Table of Content
[Naive Approach] Recursive Method – O(n^2) Time and O(h) Space
[Expected Approach] Using Bottom-Up Manner- O(n) Time and
O(h) Space
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
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
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
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
https://www.geeksforgeeks.org/check-if-removing-an-edge-can-divide-a-binary-tree-in-two-halves/?ref=lbp 6/6