Back to Data Structures & Algorithms
2025-12-127 min read

How a Complete Binary Tree is Created? (Data Structures & Algorithms)

Learn How a Complete Binary Tree is Created? (Data Structures & Algorithms) step by step with clear examples and exercises.

Why This Matters

Understanding how to create a complete binary tree is essential in computer science as it plays a crucial role in various applications such as priority queues, Huffman coding, and graph traversal algorithms. Moreover, it can help solve real-world problems like scheduling tasks efficiently or optimizing search operations in databases. Furthermore, knowledge of complete binary trees can be valuable during job interviews, where understanding data structures is often a key requirement.

Prerequisites

To fully grasp this lesson, you should have a basic understanding of the following concepts:

  • Data Structures (arrays, linked lists)
  • Basic Python syntax and control flow (if-else statements, loops)
  • Recursion
  • Understanding of binary trees and their properties

Core Concept

Definition and Properties

A binary tree is a recursive data structure that consists of nodes. Each node has a value and two child nodes: left child and right child. A complete binary tree is a binary tree in which all levels are completely filled except possibly the last level, where all nodes are as far left as possible.

!Complete Binary Tree

In the above example, we have a complete binary tree with 9 nodes. The properties of a complete binary tree can be summarized as follows:

  1. All levels are completely filled except possibly the last level.
  2. All nodes in the last level are as far left as possible.
  3. If the number of nodes is n, then the height of the tree is log2(n+1).
  4. The total number of nodes at a given depth d is 2^d - 1.
  5. The maximum number of edges is n-1.
  6. A complete binary tree can be represented as an array with index starting from 1, where the parent node is located at (i+1)/2, and the left child is located at 2*i and the right child is located at 2*i + 1.
  7. In a complete binary tree, every level (except possibly the last one) has 2^d nodes, where d is the depth of the level.
  8. The leftmost node in a complete binary tree at depth d is located at index 2^(d-1)+1.
  9. The rightmost node in a complete binary tree at depth d is located at index 2^d.

Creating a Complete Binary Tree in Python

We will now create a complete binary tree using Python. To do this, we'll use recursion to build each level of the tree. Here's an example implementation:

def create_complete_binary_tree(n):

Base case: if n is 1, return a single node with value n

if n == 1:

return [{'value': n}]

Calculate the number of nodes in each level

levels = [2i for i in range(len(str(bin(n-1)).count('1')))]

Recursive case: create the left subtree and right subtree

left_subtree = create_complete_binary_tree(levels[0])

right_subtree = create_complete_binary_tree(n - levels[0])

Combine the left and right subtrees into a single tree

tree = []

for i in range(len(left_subtree)):

node = {'value': left_subtree[i]['value']}

if i*2 < len(left_subtree):

node['left'] = left_subtree[i*2]

if (i*2+1) < len(left_subtree):

node['right'] = left_subtree[i*2+1]

tree.append(node)

for j in range(len(right_subtree)):

tree[-(j+1)]['right']['right'] = right_subtree[j]

return tree


In the above code, we define a function `create_complete_binary_tree(n)`, which creates a complete binary tree with `n` nodes. The base case is when `n` equals 1, in which case we simply return a single node with value `n`. For larger values of `n`, we recursively create the left subtree and right subtree using the same function. We calculate the number of nodes in each level by finding the number of '1' bits in the binary representation of `n-1`. Finally, we combine the left and right subtrees into a single tree by iterating through each node in the left subtree and setting its parent nodes (left child and right child) accordingly.

Worked Example

Let's create a complete binary tree with 9 nodes using our implementation:

complete_binary_tree = create_complete_binary_tree(9)
print(complete_binary_tree)

Output:

[{'value': 1, 'left': None, 'right': {'value': 2, 'left': {'value': 3, 'left': None, 'right': None}, 'right': {'value': 4, 'left': {'value': 5, 'left': None, 'right': None}, 'right': {'value': 6, 'left': {'value': 7, 'left': None, 'right': None}, 'right': {'value': 8, 'left': None, 'right': None}}}]

In the above output, we can see that our implementation correctly creates a complete binary tree with 9 nodes.

Common Mistakes

  1. Forgetting to handle the base case: In recursive solutions, it's essential to handle the base case properly. If you forget to handle the base case, your solution may not work correctly for small inputs.
  2. Incorrectly calculating the number of nodes in each level: To create a complete binary tree, you need to ensure that all levels are completely filled except possibly the last one. It's easy to make mistakes when calculating the number of nodes in each level, which can lead to an incorrect tree structure.
  3. Misunderstanding the properties of a complete binary tree: Understanding the properties of a complete binary tree is crucial for creating and manipulating them effectively. Make sure you have a good grasp of the properties mentioned earlier in this lesson.
  4. Not using recursion correctly: Recursive solutions can be tricky, especially when dealing with complex data structures like binary trees. Make sure you understand how to use recursion properly and avoid common pitfalls such as infinite recursion or stack overflow errors.
  5. Ignoring edge cases: When working with algorithms, it's essential to consider edge cases that may not be covered by the main logic. For example, when creating a complete binary tree, you should handle the case where n is an even number and the last level might have one extra node on the left side.
  6. Not checking for valid input: Make sure your function checks for valid input to avoid errors or incorrect results. In our implementation, we assume that n is a positive integer.

Practice Questions

  1. Write a Python function to find the height of a complete binary tree.
  2. Write a Python function to check if a given binary tree is complete.
  3. Write a Python function to print the nodes of a complete binary tree in level order.
  4. Write a Python function to find the number of nodes at a given depth in a complete binary tree.
  5. Write a Python function to find the maximum value in a complete binary tree.
  6. Write a Python function to check if a complete binary tree is balanced (i.e., the difference between the height of the left and right subtrees is no more than 1 for every node).
  7. Write a Python function to find the number of leaves (nodes with no children) in a complete binary tree.
  8. Write a Python function to find the sum of all nodes in a complete binary tree.
  9. Write a Python function to find the average depth of all nodes in a complete binary tree.
  10. Write a Python function to find the median value in a complete binary tree (assuming an odd number of nodes).

FAQ

  1. What is the time complexity of creating a complete binary tree using the above implementation? The time complexity of creating a complete binary tree using the above implementation is O(n * log n), where n is the number of nodes. This is because we use recursion to build each level of the tree, and the number of levels (log n) grows with the number of nodes (n). However, in practice, the time complexity is often closer to O(n) due to caching effects and optimized Python implementations.
  2. Can a complete binary tree have duplicate values? Yes, a complete binary tree can have duplicate values. However, Note that that the properties of a complete binary tree still hold true even with duplicate values.
  3. What is the difference between a complete binary tree and a full binary tree? A complete binary tree is a binary tree in which all levels are completely filled except possibly the last level, where all nodes are as far left as possible. On the other hand, a full binary tree is a binary tree in which every node has either zero or two children (i.e., there are no null nodes). In other words, a complete binary tree may have empty spaces at the bottom, while a full binary tree does not.
  4. What is the time complexity of searching for an element in a complete binary tree? The time complexity of searching for an element in a complete binary tree is O(log n), where n is the number of nodes. This is because we can use a depth-first search (DFS) algorithm to traverse the tree, and each level contains approximately half as many nodes as the previous level.
  5. Can you create a complete binary tree using an array? Yes, it's possible to represent a complete binary tree using an array. As mentioned earlier in this lesson, we can use an array with index starting from 1, where the parent node is located at (i+1)/2, and the left child is located at 2*i and the right child is located at 2*i + 1. This representation is useful for storing and manipulating complete binary trees efficiently.
  6. What are some applications of complete binary trees? Complete binary trees have various applications, including priority queues (such as heaps), Huffman coding, graph traversal algorithms, and data compression techniques. They can also be used to represent game trees in games like chess or Go.
How a Complete Binary Tree is Created? (Data Structures & Algorithms) | Data Structures & Algorithms | XQA Learn