Back to Data Structures & Algorithms
2026-04-226 min read

Complete Binary Tree (Data Structures & Algorithms)

Learn Complete Binary Tree (Data Structures & Algorithms) step by step with clear examples and exercises.

Title: Complete Binary Tree (Data Structures & Algorithms) - Python Examples

Why This Matters

A complete binary tree is a crucial data structure to understand, as it helps optimize search and insertion operations in competitive programming. This lesson will delve into the core concepts, worked examples, common mistakes, practice questions, and frequently asked questions about complete binary trees using Python examples.

Prerequisites

To fully grasp the concepts of a complete binary tree, you should have a solid understanding of:

  1. Basic data structures like arrays, lists, and linked lists in Python.
  2. Basic Python syntax, including functions, loops, and conditional statements.
  3. Binary trees and their properties (including binary search trees).
  4. Big O notation for analyzing algorithm efficiency.
  5. Familiarity with recursion is also beneficial but not strictly required.

Core Concept

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. In other words, each level of the tree has the maximum number of nodes, and any remaining nodes are placed at the lowest level from left to right.

Here's an example of a complete binary tree:

1
2 3
4 5 6 7
8 9 10 11 12 13 14

In this tree, every node has either zero or two children, and all levels except the last are full. The last level is left-justified, meaning that all nodes are as far left as possible.

Complete Binary Tree Properties

  1. Every level, except possibly the last, is completely filled.
  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 h = log2(n+1) - 1.
  4. The total number of nodes in a complete binary tree with h levels is 2^(h+1) - 1.
  5. Complete binary trees are often used to represent priority queues efficiently.

Worked Example

Let's create a complete binary tree using Python:

class Node:
def __init__(self, key):
self.left = None
self.right = None
self.val = key

def insert(self, key):
if not self.val:
self.val = key
else:
if self.val < key:
if self.right is None:
self.right = Node(key)
else:
self.right.insert(key)
else:
if self.left is None:
self.left = Node(key)
else:
self.left.insert(key)

def is_complete(self):
return self._is_complete(self, self.height()) - 1 == self.size()

def _is_complete(self, node, height):
if node is None:
return 0
if height == 0:
return 1
left_size = node.left.size() if node.left else 0
right_size = node.right.size() if node.right else 0
return max(left_size, right_size) + self._is_complete(node.left if left_size >= right_size else node.right, height - 1)

def height(self):
if not self.val:
return 0
return 1 + max(self.left.height() if self.left else 0, self.right.height() if self.right else 0)

def size(self):
return 1 + (self.left.size() if self.left else 0) + (self.right.size() if self.right else 0)

def create_complete_tree():
root = Node(1)
root.insert(2)
root.insert(3)
root.left.insert(4)
root.left.insert(5)
root.right.insert(6)
root.right.insert(7)
root.left.right.insert(8)
root.left.right.insert(9)
root.right.left.insert(10)
root.right.left.insert(11)
root.right.right.insert(12)
root.right.right.insert(13)
root.right.right.insert(14)
return root

def main():
tree = create_complete_tree()
print("Is the tree complete? ", tree.is_complete())

if __name__ == "__main__":
main()

In this example, we define a Node class to represent each node in the binary tree. The insert function takes a node and a key value and inserts a new node with the given key as a child of the provided node. The is_complete function checks if the given tree is complete by traversing the tree level-by-level, ensuring that every level except the last is full and that the last level is left-justified.

Common Mistakes

  1. Incorrect implementation of insertion: Make sure to implement insertion in such a way that the tree remains complete after each operation. This may require careful handling of edge cases, like when inserting a new node at the bottom level.
  2. Not checking for fullness on every level: It's essential to check the fullness of every level during traversal to ensure the tree is truly complete.
  3. Ignoring left-justification: The last level should be left-justified, meaning that all nodes are as far left as possible. Ensure your implementation enforces this property.
  4. Assuming a complete binary tree can have only one child per node: In a complete binary tree, every node has either zero or two children.
  5. Not considering the base case for recursive functions: When implementing recursive functions like is_complete, make sure to handle the base case properly (e.g., when the node is None).

Common Mistakes - Practice Questions

  1. What happens if you insert more than 2^n nodes into a binary tree?
  2. Can a complete binary tree have duplicate keys? If so, how does it affect the properties of the tree?
  3. How can you optimize the is_complete function to handle large trees more efficiently?
  4. What is the time complexity of inserting a node into a complete binary tree using recursion?

Practice Questions

  1. Implement a function to find the height of a complete binary tree using Python.
  2. Write a function to check if a given binary tree is a complete binary tree using recursion in Python.
  3. Given a list of integers, construct a complete binary tree with these values using Python.
  4. Find the number of nodes at each level in a complete binary tree with n nodes using Python.
  5. Implement an efficient method to insert a new node into a complete binary tree without changing its completeness property.
  6. Write a function to print a complete binary tree in a visually appealing manner.
  7. Given a complete binary tree, find the maximum sum path from any node to any leaf node.
  8. Implement a function to find the k-th smallest element in a complete binary tree.

FAQ

  1. What happens if I insert more than 2^n nodes into a binary tree?: Inserting more nodes will make the tree no longer a complete binary tree, as some levels will become full before others.
  2. Can a complete binary tree have duplicate keys?: Yes, a complete binary tree can contain duplicate keys, but it does not affect its completeness or properties.
  3. What is the time complexity of inserting a node into a complete binary tree?: The time complexity of inserting a node into a complete binary tree is O(log n), assuming that the tree is balanced and the height of the tree is logarithmic in the number of nodes.
  4. How can I print a complete binary tree in a visually appealing manner?: You can use various techniques to print a complete binary tree in a visually appealing manner, such as using spaces for indentation, printing node values on separate lines, or using ASCII art.
  5. What is the maximum sum path from any node to any leaf node in a complete binary tree?: The maximum sum path from any node to any leaf node in a complete binary tree can be found by traversing the tree and keeping track of the maximum sum encountered so far. This problem can be solved using dynamic programming or recursion with memoization.
  6. How can I find the k-th smallest element in a complete binary tree?: To find the k-th smallest element in a complete binary tree, you can use a modified inorder traversal algorithm that keeps track of the number of nodes visited and returns the k-th node encountered. This problem can be solved using recursion or iteration with appropriate data structures like stacks or queues.
Complete Binary Tree (Data Structures & Algorithms) | Data Structures & Algorithms | XQA Learn