Leetcode 958: Check Completeness of a Binary Tree

grid47
grid47
Exploring patterns and algorithms
Aug 3, 2024 5 min read

You are given the root of a binary tree. Determine if the tree is a complete binary tree. A complete binary tree is defined as follows: every level, except possibly the last, is completely filled, and all nodes in the last level are as far left as possible.
Problem
Approach
Steps
Complexity
Input: The input consists of the root of a binary tree represented by the 'TreeNode' structure, where each node has a value, a left child, and a right child.
Example: Input: root = [1, 2, 3, 4, 5, 6]
Constraints:
• The number of nodes in the tree is between 1 and 100.
• 1 <= Node.val <= 1000.
Output: Return true if the binary tree is a complete binary tree, otherwise return false.
Example: Output: true
Constraints:
• The function should return a boolean indicating whether the tree is complete.
Goal: The goal is to verify that every level, except possibly the last, is completely filled and that all nodes in the last level are as far left as possible.
Steps:
• 1. Traverse the binary tree using level-order traversal.
• 2. At each step, check if the current node is null. If it is null, ensure that no nodes exist after it in the same level.
• 3. If all levels are filled correctly and the last level's nodes are as far left as possible, return true. Otherwise, return false.
Goal: The input tree must adhere to the constraints of having between 1 and 100 nodes, with node values between 1 and 1000.
Steps:
• The tree will contain between 1 and 100 nodes.
• Node values will be between 1 and 1000.
Assumptions:
• The binary tree is provided as a 'TreeNode' object.
Input: Input: root = [1, 2, 3, 4, 5, 6]
Explanation: In this case, every level before the last is filled completely, and all nodes in the last level are as far left as possible. Therefore, the tree is a complete binary tree.

Input: Input: root = [1, 2, 3, 4, 5, null, 7]
Explanation: In this case, the node with value 7 is not as far left as possible in the last level. Therefore, the tree is not a complete binary tree.

Link to LeetCode Lab


LeetCode Solutions Library / DSA Sheets / Course Catalog
comments powered by Disqus