[LeetCode] 958. Check Completeness of a Binary Tree

9次阅读

共计 614 个字符,预计需要花费 2 分钟才能阅读完成。

Problem
Given 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 2^h nodes inclusive at the last level h.
Solution
class Solution {
public boolean isCompleteTree(TreeNode root) {
if (root == null) return true;
Queue<TreeNode> queue = new LinkedList<>();
queue.offer(root);
boolean lastLevel = false;
while (!queue.isEmpty()) {
TreeNode cur = queue.poll();
if (cur == null) lastLevel = true;
else {
if (lastLevel) return false;
queue.offer(cur.left);
queue.offer(cur.right);
}
}
return true;
}
}

正文完
 0