今天参加周赛的题目:
完全二叉树的定义:
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.
https://leetcode.com/contest/weekly-contest-115/problems/check-completeness-of-a-binary-tree/
解法:层次遍历
public boolean isCompleteTree(TreeNode root) {
if (root == null) return true;
Queue<TreeNode> q = new LinkedList<>();
q.offer(root);
int i=0;
while (true){
int len = q.size();
for(;i<len;i++){
TreeNode e = ((LinkedList<TreeNode>) q).get(i);
if(e==null){
len = q.size();
for(;i<len;i++){
if(((LinkedList<TreeNode>) q).get(i)!=null) return false;
}
return true;
}else{
q.offer(e.left);
q.offer(e.right);
}
}
}
}
本文介绍了如何解决LeetCode周赛中的第958题,涉及完全二叉树的定义及层次遍历的解题策略。完全二叉树每个层级都完全填充,最后一层的所有节点尽可能靠左。
308

被折叠的 条评论
为什么被折叠?



