二叉树的最大深度和最小深度昨日已完成(跳过了迭代法)
完全二叉树的节点
得知完全二叉树的特点是每层都是满的,最后一层左边是满的就可以迭代每层然后放进一个节点count++,当遇到某个节点的左或右节点为空时,停止循环。
class Solution {
public int countNodes(TreeNode root) {
int count = 0;
Queue<TreeNode> qe = new LinkedList<>();
if(root!=null){qe.offer(root);count++;}
while(qe.size()!=0){
int size = qe.size();
while(size>0){
TreeNode cur = qe.poll();
if(cur.left!=null){qe.offer(cur.left);count++;}
else{return count;}
if(cur.right!=null){qe.offer(cur.right);count++;}
else{return count;}
size--;
}
}
return count;
}
}
类似于代码随想录中给出的题解迭代
今天时间有点紧利用完全二叉树特性解题的方式明天补。