Tutorialspoint
Problem
Solution
Submissions

Complete Binary Tree

Certification: Intermediate Level Accuracy: 0% Submissions: 0 Points: 10

Write a C# program to determine if a given binary tree is a complete binary tree. A complete binary tree is a binary tree in which every level, except possibly the last, is completely filled, and all nodes in the last level are as far left as possible.

Example 1
  • Input:

    Biinary Tree Except Fully Last Level

  • Output: true
  • Explanation:
    • Every level is filled except the last level, and all nodes in the last level are as far left as possible.
Example 2
  • Input:

    Binary Tree Not Filled From Left to Right

  • Output: false
  • Explanation:
    • The last level is not filled from left to right. Node 7 is on the right side without having a left sibling.
Constraints
  • The number of nodes in the tree is between 1 and 10^4
  • -1000 ≤ Node.val ≤ 1000
  • Time Complexity: O(n) where n is the number of nodes
  • Space Complexity: O(n) for the queue in a level-order traversal
Binary TreeTreeWalmartArctwist
Editorial

Login to view the detailed solution and explanation for this problem.

My Submissions
All Solutions
Lang Status Date Code
You do not have any submissions for this problem.
User Lang Status Date Code
No submissions found.

Please Login to continue
Solve Problems

 
 
 
Output Window

Don't have an account? Register

Solution Hints

  • Use a level-order traversal (BFS) to check if the tree is complete.
  • Keep track of whether we've seen a non-full node (a node with missing children).
  • If we ever encounter a node after seeing a non-full node, the tree is not complete.
  • A non-full node is one that either has no left child or has a left child but no right child.
  • All nodes after a non-full node should be leaf nodes.

Steps to solve by this approach:

 Step 1: Handle the base case where the root is null (an empty tree is complete by definition).
 Step 2: Perform a level-order traversal using a queue, starting with the root node.
 Step 3: For each node, check if it has a left child and a right child.
 Step 4: If a node doesn't have a left child or right child, mark that we've seen a non-full node.
 Step 5: If we encounter a node with a child after seeing a non-full node, the tree is not complete.
 Step 6: If we complete the traversal without finding any violations, the tree is complete.
 Step 7: Return true if the tree passes all checks.

Submitted Code :