LeetCode 958. Check Completeness of a Binary Tree
the definition of complete binary tree is:
all the leaf nodes should be as left as it can be. and every other level is full except the bottom node level
it remind me of the recursion way. but after i write the following codes, it’s not working
class Solution {
public boolean isCompleteTree(TreeNode root) {
if (root == null) return true;
if (root.left == null && root.right != null) {
return false;
}
return isCompleteTree(root.left) && isCompleteTree(root.right);
}
}
it’s not working because it’s not correct. because this equation:
isCompleteTree(TreeNode root) = isCompleteTree(root.left) && isCompleteTree(root.right); is not right! we have to make sure every level is full until the last one level.
so we should do a level order traverse, and we should keep in mind that when we check the results, there should be any nodes after we meet with a null.
but I don’t know how to implement it even though it is very clear.
class Solution {
public boolean isCompleteTree(TreeNode root) {
if (root == null) return true;
Queue<TreeNode> queue = new LinkedList<>();
TreeNode cur = root;
queue.offer(cur);
while (queue.peek() != null) {
TreeNode node = queue.poll();
queue.offer(node.left);
queue.offer(node.right); //
}
while (!queue.isEmpty() && queue.peek() == null) {
queue.poll();
}
return queue.isEmpty();
}
}
I get the general idea but the code is still difficult for me to implement

浙公网安备 33010602011771号