Skip to content

Commit be4fcbc

Browse files
authored
Create README.md
1 parent 21dc212 commit be4fcbc

File tree

1 file changed

+168
-0
lines changed
  • 19 - Heap Data Structure Problems/04 - Check Completeness of a Binary Tree

1 file changed

+168
-0
lines changed
Lines changed: 168 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,168 @@
1+
<h1 align='center'>Check - Completeness - of a - Binary - Tree</h1>
2+
3+
## Problem Statement
4+
5+
**Problem URL :** [Check Completeness of a Binary Tree](https://leetcode.com/problems/check-completeness-of-a-binary-tree/)
6+
7+
![image](https://github.com/user-attachments/assets/5a659007-a46b-43a9-8bc8-ecbe1bb7af1f)
8+
![image](https://github.com/user-attachments/assets/c8d2bab9-d26c-4614-b6a4-1579387efe64)
9+
10+
## Problem Explanation
11+
**Problem Statement**: In this problem, we need to determine if a given binary tree is a "complete binary tree." A binary tree is considered complete if all levels except possibly the last are fully filled, and all nodes are as far left as possible on the last level.
12+
13+
**Example of a Complete Binary Tree**:
14+
```
15+
1
16+
/ \
17+
2 3
18+
/ \ /
19+
4 5 6
20+
```
21+
22+
This tree is complete since all levels except the last are fully filled, and the nodes on the last level are left-aligned.
23+
24+
**Example of an Incomplete Binary Tree**:
25+
```
26+
1
27+
/ \
28+
2 3
29+
\
30+
5
31+
```
32+
33+
This tree is not complete because node `5` is not as far left as possible.
34+
35+
**Approach**:
36+
1. First, count the total number of nodes in the tree (`totalCount`).
37+
2. Use a recursive function (`isCBT`) to verify if the tree satisfies the completeness condition by following the index rules for a complete binary tree. In a complete binary tree:
38+
- The left child of a node at index `i` is located at index `2 * i + 1`.
39+
- The right child is at index `2 * i + 2`.
40+
3. If at any point an index exceeds the total number of nodes, the tree is not complete.
41+
42+
## Problem Solution
43+
```cpp
44+
/**
45+
* Definition for a binary tree node.
46+
* struct TreeNode {
47+
* int val;
48+
* TreeNode *left;
49+
* TreeNode *right;
50+
* TreeNode() : val(0), left(nullptr), right(nullptr) {}
51+
* TreeNode(int x) : val(x), left(nullptr), right(nullptr) {}
52+
* TreeNode(int x, TreeNode *left, TreeNode *right) : val(x), left(left), right(right) {}
53+
* };
54+
*/
55+
class Solution {
56+
public:
57+
int totalCount(TreeNode* root){
58+
if(root == NULL) return 0;
59+
60+
return 1 + totalCount(root -> left) + totalCount(root -> right);
61+
}
62+
int isCBT(TreeNode* root, int index, int count){
63+
if(root == NULL) return true;
64+
if(index >= count) return false;
65+
66+
bool left = isCBT(root -> left, 2 * index + 1, count);
67+
bool right = isCBT(root -> right, 2 * index + 2, count);
68+
69+
return left && right;
70+
}
71+
bool isCompleteTree(TreeNode* root) {
72+
int index = 0;
73+
int count = totalCount(root);
74+
return isCBT(root, index, count);
75+
}
76+
};
77+
```
78+
79+
## Problem Solution Explanation
80+
81+
```cpp
82+
class Solution {
83+
public:
84+
// Helper function to count the total nodes in the tree.
85+
int totalCount(TreeNode* root){
86+
if(root == NULL) return 0;
87+
88+
return 1 + totalCount(root -> left) + totalCount(root -> right);
89+
}
90+
```
91+
- **`totalCount` Function**: This function calculates the total number of nodes in the tree.
92+
- If the `root` is `NULL`, it returns `0` (no nodes).
93+
- Otherwise, it recursively counts the nodes in the left and right subtrees and adds `1` for the current node.
94+
95+
```cpp
96+
int isCBT(TreeNode* root, int index, int count){
97+
if(root == NULL) return true;
98+
if(index >= count) return false;
99+
100+
bool left = isCBT(root -> left, 2 * index + 1, count);
101+
bool right = isCBT(root -> right, 2 * index + 2, count);
102+
103+
return left && right;
104+
}
105+
```
106+
- **`isCBT` Function**: This function recursively checks whether the binary tree is complete.
107+
- If `root` is `NULL`, it returns `true` (an empty tree is considered complete).
108+
- If `index >= count`, it returns `false`, as it implies that a node at this position should not exist in a complete binary tree with `count` nodes.
109+
- It recursively checks the left and right subtrees with updated indices based on the formula for complete binary trees (`2 * index + 1` for left child and `2 * index + 2` for right child).
110+
- Finally, it returns `true` only if both left and right subtrees are complete.
111+
112+
```cpp
113+
bool isCompleteTree(TreeNode* root) {
114+
int index = 0;
115+
int count = totalCount(root);
116+
return isCBT(root, index, count);
117+
}
118+
};
119+
```
120+
- **`isCompleteTree` Function**: This function initiates the process of checking completeness.
121+
- First, it calculates the total node count with `totalCount`.
122+
- Then it calls `isCBT` to check the completeness of the tree from the root.
123+
124+
### Step 3: Examples and Explanation
125+
126+
1. **Example 1**:
127+
- **Tree**:
128+
```
129+
1
130+
/ \
131+
2 3
132+
/ \
133+
4 5
134+
```
135+
- **Process**:
136+
- `totalCount` calculates `count = 5`.
137+
- `isCBT` is called for each node, validating the left and right subtrees according to index constraints.
138+
- Output: **`true`** (This is a complete binary tree).
139+
140+
2. **Example 2**:
141+
- **Tree**:
142+
```
143+
1
144+
/ \
145+
2 3
146+
/
147+
4
148+
```
149+
- **Process**:
150+
- `totalCount` calculates `count = 4`.
151+
- `isCBT` identifies that `node 4` is not at the leftmost position on its level.
152+
- Output: **`false`** (This is not a complete binary tree).
153+
154+
### Step 4: Time and Space Complexity
155+
156+
- **Time Complexity**:
157+
- `totalCount` traverses all nodes, making its time complexity **O(N)**.
158+
- `isCBT` also traverses all nodes, so it has a time complexity of **O(N)**.
159+
- Overall, the time complexity is **O(N)**.
160+
161+
- **Space Complexity**:
162+
- The recursion in `totalCount` and `isCBT` could go as deep as the height of the tree, making the space complexity **O(H)**, where `H` is the height of the tree. In the worst case (skewed tree), `H` can be `N`, but in a balanced tree, `H` is `log N`.
163+
164+
### Step 5: Recommendations
165+
166+
- **Handling Edge Cases**: Ensure to handle edge cases like an empty tree or a tree with a single node.
167+
- **Alternative Approach**: A level-order traversal could also be used to check completeness level by level, which might be easier to understand for some cases.
168+
- **Practice**: Try to manually trace through different binary tree structures to gain confidence in understanding completeness conditions.

0 commit comments

Comments
 (0)