https://github.com/emahtab/check-completeness-of-a-binary-tree
Checking whether a binary tree is Complete binary tree or not
https://github.com/emahtab/check-completeness-of-a-binary-tree
bfs complete-binary-tree leetcode problem
Last synced: 7 months ago
JSON representation
Checking whether a binary tree is Complete binary tree or not
- Host: GitHub
- URL: https://github.com/emahtab/check-completeness-of-a-binary-tree
- Owner: eMahtab
- Created: 2020-02-01T16:47:51.000Z (over 5 years ago)
- Default Branch: master
- Last Pushed: 2020-05-30T05:55:18.000Z (over 5 years ago)
- Last Synced: 2025-02-02T03:26:14.670Z (9 months ago)
- Topics: bfs, complete-binary-tree, leetcode, problem
- Homepage:
- Size: 4.88 KB
- Stars: 1
- Watchers: 1
- Forks: 0
- Open Issues: 0
-
Metadata Files:
- Readme: README.md
Awesome Lists containing this project
README
# Check Completeness of a Binary tree
## https://leetcode.com/problems/check-completeness-of-a-binary-treeGiven a binary tree, determine if it is a complete binary tree.
Definition of a complete binary tree from Wikipedia:
In a complete binary tree every level, except possibly the last, is completely filled, and all nodes in the last level are as far left as possible. It can have between 1 and 2h nodes inclusive at the last level h.**Note: The tree will have between 1 and 100 nodes.**
## Implementation :
```java
/**
* Definition for a binary tree node.
* public class TreeNode {
* int val;
* TreeNode left;
* TreeNode right;
* TreeNode(int x) { val = x; }
* }
*/
class Solution {
public boolean isCompleteTree(TreeNode root) {
if(root == null)
return true;
Queue queue = new LinkedList<>();
queue.offer(root);
boolean nullSeen = false;
while(!queue.isEmpty()){
TreeNode current = queue.poll();
if(current == null){
nullSeen = true;
} else {
// If we already saw a null node
// and then If we see a non null node, that means its not a complete binary tree
if(nullSeen)
return false;
queue.offer(current.left);
queue.offer(current.right);
}
}
return true;
}
}
```
## Little Refactoring
```java
class Solution {
public boolean isCompleteTree(TreeNode root) {
if(root == null)
return true;
Queue q = new LinkedList<>();
q.add(root);
boolean nullSeen = false;
while(!q.isEmpty()) {
TreeNode node = q.poll();
if(node == null)
nullSeen = true;
else if(nullSeen)
return false;
else {
q.add(node.left);
q.add(node.right);
}
}
return true;
}
}
```# References :
https://www.youtube.com/watch?v=j16cwbLEf9w