讨论/《零起步学算法》 - 练习:完全二叉树的节点个数/
《零起步学算法》 - 练习:完全二叉树的节点个数
共 1 个回复

一把过

class Solution {
    public int countNodes(TreeNode root) {
      if(root == null) {
        return 0;
      }
      //广度优先搜索 => 层序遍历 => bfs
      Deque<TreeNode> queue = new LinkedList<>();
      queue.offer(root);
      int sum = 0;
      while(!queue.isEmpty()) {
        TreeNode head = queue.poll();
        sum++;
        TreeNode leftNode = head.left;
        TreeNode rightNode = head.right;
        if(leftNode != null) {
          queue.offer(leftNode);
        }
        if(rightNode != null) {
          queue.offer(rightNode);
        }
      }
      return sum;
    }
}
1