Coding questions · Meta
Validate complete binary tree
This question evaluates understanding of binary tree structure and the ability to validate completeness, testing competency in tree data structures and algorithmic reasoning.
You are given the root of a binary tree.
A complete binary tree is defined as a binary tree in which:
- Every level, except possibly the last, is completely filled.
- All nodes in the last level are as far left as possible.
Write a function that determines whether the given binary tree is complete.
Return true if the tree is complete, and false otherwise.
You may assume the tree nodes are defined as:
class TreeNode {
int val;
TreeNode left;
TreeNode right;
}
Examples:
- Input tree:
1
/ \
2 3
/ \ /
4 5 6
Output: true (all levels are filled except the last, and the last level is left-aligned).
- Input tree:
1
/ \
2 3
/ \ \
4 5 7
Output: false (node 3 is missing a left child but has a right child, so nodes in the last level are not as far left as possible).
Constraints:
- The number of nodes in the tree is in the range
[1, 10^4]. - Node values are arbitrary integers and are not necessarily unique.
Validate Complete Binary Tree
Trees are [value,left,right]. Return whether the tree is complete using level-order gap detection.
Hints
- Clarify edge cases before coding.
- Keep the return value deterministic.