222. 完全二叉树的节点个数
方法一:层序遍历
/**
* Definition for a binary tree node.
* public class TreeNode {
* int val;
* TreeNode left;
* TreeNode right;
* TreeNode() {}
* TreeNode(int val) { this.val = val; }
* TreeNode(int val, TreeNode left, TreeNode right) {
* this.val = val;
* this.left = left;
* this.right = right;
* }
* }
*/
class Solution {
public int countNodes(TreeNode root) {
int count = 0;
if(root == null) return 0;
Queue<TreeNode> queue = new LinkedList<>();
queue.offer(root);
while(!queue.isEmpty()){
int n = queue.size();
while(n > 0){
TreeNode node = queue.poll();
count++;
if(node.left != null) queue.offer(node.left);
if(node.right != null) queue.offer(node.right);
n--;
}
}
return count;
}
}
注:今日状态不好,水每日打卡一次~