For working professionals
For fresh graduates
More
1. Introduction
6. PyTorch
9. AI Tutorial
10. Airflow Tutorial
11. Android Studio
12. Android Tutorial
13. Animation CSS
16. Apex Tutorial
17. App Tutorial
18. Appium Tutorial
21. Armstrong Number
22. ASP Full Form
23. AutoCAD Tutorial
27. Belady's Anomaly
30. Bipartite Graph
35. Button CSS
39. Cobol Tutorial
46. CSS Border
47. CSS Colors
48. CSS Flexbox
49. CSS Float
51. CSS Full Form
52. CSS Gradient
53. CSS Margin
54. CSS nth Child
55. CSS Syntax
56. CSS Tables
57. CSS Tricks
58. CSS Variables
61. Dart Tutorial
63. DCL
65. DES Algorithm
83. Dot Net Tutorial
86. ES6 Tutorial
91. Flutter Basics
92. Flutter Tutorial
95. Golang Tutorial
96. Graphql Tutorial
100. Hive Tutorial
103. Install Bootstrap
107. Install SASS
109. IPv 4 address
110. JCL Programming
111. JQ Tutorial
112. JSON Tutorial
113. JSP Tutorial
114. Junit Tutorial
115. Kadanes Algorithm
116. Kafka Tutorial
117. Knapsack Problem
118. Kth Smallest Element
119. Laravel Tutorial
122. Linear Gradient CSS
129. Memory Hierarchy
133. Mockito tutorial
134. Modem vs Router
135. Mulesoft Tutorial
136. Network Devices
138. Next JS Tutorial
139. Nginx Tutorial
141. Octal to Decimal
142. OLAP Operations
143. Opacity CSS
144. OSI Model
145. CSS Overflow
146. Padding in CSS
148. Perl scripting
149. Phases of Compiler
150. Placeholder CSS
153. Powershell Tutorial
158. Pyspark Tutorial
161. Quality of Service
162. R Language Tutorial
164. RabbitMQ Tutorial
165. Redis Tutorial
166. Redux in React
167. Regex Tutorial
170. Routing Protocols
171. Ruby On Rails
172. Ruby tutorial
173. Scala Tutorial
175. Shadow CSS
178. Snowflake Tutorial
179. Socket Programming
180. Solidity Tutorial
181. SonarQube in Java
182. Spark Tutorial
189. TCP 3 Way Handshake
190. TensorFlow Tutorial
191. Threaded Binary Tree
196. Types of Queue
197. TypeScript Tutorial
198. UDP Protocol
202. Verilog Tutorial
204. Void Pointer
205. Vue JS Tutorial
206. Weak Entity Set
207. What is Bandwidth?
208. What is Big Data
209. Checksum
211. What is Ethernet
214. What is ROM?
216. WPF Tutorial
217. Wireshark Tutorial
218. XML Tutorial
Complete binary trees are fascinating structures in the realm of data structures and algorithms. They possess unique properties and offer efficient representation, making them valuable in various applications. In this article, we will explore complete binary trees comprehensively, understanding their definition, properties, creation, algorithms, and practical implementations.
A complete binary tree is a binary tree in which all levels, except possibly the last one, are completely filled and all nodes are left-justified. It is a balanced structure that ensures efficient storage and retrieval of data. Complete binary trees have crucial applications in areas like heap data structures, binary heaps, and binary search trees.
A complete binary tree can be visualized as a binary tree where all levels, except the last one, are filled with nodes. In the last level, nodes are filled from left to right without any gaps. This unique property ensures that the tree is perfectly balanced. Let's consider an example to understand this better.
Example:
In this example, the tree is a complete binary tree, as all levels are filled except for the last level, where the nodes are filled from left to right.
Before we delve deeper into complete binary trees, let's familiarize ourselves with some essential terminology:
Complete binary trees possess several key properties that distinguish them from other tree structures:
To create a complete binary tree, a specific algorithm is followed. Let's explore the steps involved in creating a complete binary tree.
Algorithm:
Intuition Behind the Algorithm:
The algorithm ensures that the nodes are added to the tree level by level from left to right, maintaining the complete binary tree structure. By using a queue, we can process the nodes in a First-In-First-Out (FIFO) manner, ensuring the correct order of insertion.
Complete binary tree example:
This makes an almost complete binary tree.
By following the algorithm, we successfully create a complete binary tree.
Checking If a Binary Tree is a Complete Binary Tree
To determine if a binary tree is a complete binary tree, we can use various methods. Let's explore two popular approaches in Java and C++.
import java.util.LinkedList;
import java.util.Queue;
class TreeNode {
int val;
TreeNode left;
TreeNode right;
TreeNode(int val) {
this.val = val;
}
}
public class CompleteBinaryTreeChecker {
public static void main(String[] args) {
// Create a sample binary tree
TreeNode root = new TreeNode(1);
root.left = new TreeNode(2);
root.right = new TreeNode(3);
root.left.left = new TreeNode(4);
root.left.right = new TreeNode(5);
root.right.left = new TreeNode(6);
// Check if the binary tree is complete
boolean isComplete = isCompleteBinaryTree(root);
// Print the result
System.out.println("Is the binary tree complete? " + isComplete);
}
public static boolean isCompleteBinaryTree(TreeNode root) {
Queue<TreeNode> queue = new LinkedList<>();
queue.offer(root);
boolean isLastLevel = false;
while (!queue.isEmpty()) {
TreeNode current = queue.poll();
if (current == null) {
isLastLevel = true;
} else {
if (isLastLevel) {
return false;
}
queue.offer(current.left);
queue.offer(current.right);
}
}
return true;
}
}
#include <queue>
struct TreeNode {
int val;
TreeNode* left;
TreeNode* right;
TreeNode(int val) : val(val), left(nullptr), right(nullptr) {}
};
bool isCompleteBinaryTree(TreeNode* root) {
std::queue<TreeNode*> queue;
queue.push(root);
bool isLastLevel = false;
while (!queue.empty()) {
TreeNode* current = queue.front();
queue.pop();
if (current == nullptr) {
isLastLevel = true;
} else {
if (isLastLevel) {
return false;
}
queue.push(current->left);
queue.push(current->right);
}
}
return true;
}
int main() {
// Create a sample binary tree
TreeNode* root = new TreeNode(1);
root->left = new TreeNode(2);
root->right = new TreeNode(3);
root->left->left = new TreeNode(4);
root->left->right = new TreeNode(5);
root->right->left = new TreeNode(6);
// Check if the binary tree is complete
bool isComplete = isCompleteBinaryTree(root);
// Print the result
std::cout << "Is the binary tree complete? " << (isComplete ? "true" : "false") << std::endl;
return 0;
}
Other Methods to Check if a Binary Tree is a Complete Binary Tree or Not.
Apart from the iterative level order traversal method shown above, there are additional ways to check if a binary tree is a complete binary tree. Some popular methods include depth-first search (DFS) and recursive approaches.
Level order traversal, also known as Breadth-First Search (BFS), is a widely used technique to traverse and process binary trees. It follows the approach of processing the nodes level by level, from left to right.
Complete binary trees can be efficiently represented using arrays, providing compact storage and easy access to elements. The array representation allows us to map the complete binary tree structure onto an array.
class TreeNode {
int data;
TreeNode left;
TreeNode right;
TreeNode(int data) {
this.data = data;
}
}
public class Main {
public static void main(String[] args) {
// Create a complete binary tree
TreeNode root = new TreeNode(1);
root.left = new TreeNode(2);
root.right = new TreeNode(3);
root.left.left = new TreeNode(4);
root.left.right = new TreeNode(5);
root.right.left = new TreeNode(6);
// Create an array to store the elements of the binary tree
int[] arr = new int[7];
// Convert the complete binary tree to an array
completeBinaryTreeToArray(root, arr, 0);
// Print the array elements
for (int i = 0; i < arr.length; i++) {
System.out.print(arr[i] + " ");
}
}
public static void completeBinaryTreeToArray(TreeNode root, int[] arr, int index) {
if (root == null) {
return;
}
arr[index] = root.data;
completeBinaryTreeToArray(root.left, arr, 2 * index + 1);
completeBinaryTreeToArray(root.right, arr, 2 * index + 2);
}
}
Output:
A full binary tree is a binary tree in which every node has either 0 or 2 children. In other words, every node is either a leaf node or an internal node with two child nodes.
A complete binary tree, as discussed earlier, is a binary tree where all levels, except possibly the last one, are completely filled. It is left-justified, meaning that nodes are filled from left to right in the last level.
Complete binary trees find applications in various domains, including:
A complete binary tree is a fundamental concept in data structures. It is a type of binary tree that has unique properties and offers an efficient representation for storing and retrieving data. In a complete binary tree, all levels, except possibly the last one, are completely filled, and the nodes are left-justified. This balance ensures optimal storage and enables efficient operations.
The complete binary tree structure is often used in various applications, including heap data structures, binary heaps, and binary search trees. Its balanced nature allows for efficient searching, insertion, and deletion operations. Complete binary trees can be represented using arrays or lists, providing compact storage and easy access to elements.
A strictly binary tree is a specific type of binary tree that imposes a restriction on the number of children each node can have. In a strictly binary tree, every node can have either 0 or 2 children, but not 1 child. This means that each internal node in a strictly binary tree must always have exactly two children.
This restriction creates a balanced and predictable structure within the tree. It ensures that every level is fully occupied, resulting in a more uniform distribution of nodes and a symmetrical appearance.
Complete binary trees are considered remarkable structures that offer balance, efficient representation, and practical applications. By understanding their intricacies, properties, creation, and algorithms, we can leverage their benefits to the fullest in various domains. Whether in heap data structures or sorting algorithms, complete binary trees continue to play a crucial role in computer science and programming.
Determining whether a binary tree is complete involves checking if the tree satisfies the properties of a complete binary tree. This can be done using various methods such as level order traversal (BFS), recursive approaches, or depth-first search (DFS). By analyzing the structure and properties of the tree, you can determine if it meets the criteria of a complete binary tree.
A complete binary tree can be efficiently represented using an array. The array representation follows a specific mapping, where the root node is stored at index 0, and for any node at index 'i', its left child is located at index '2i + 1' and its right child at index '2i + 2'.
A complete binary tree can be created by using three traversals as follows:
Author
Talk to our experts. We are available 7 days a week, 9 AM to 12 AM (midnight)
Indian Nationals
1800 210 2020
Foreign Nationals
+918045604032
1.The above statistics depend on various factors and individual results may vary. Past performance is no guarantee of future results.
2.The student assumes full responsibility for all expenses associated with visas, travel, & related costs. upGrad does not provide any a.