题解 | #完全二叉树结点数#
完全二叉树结点数
http://www.nowcoder.com/practice/512688d2ecf54414826f52df4e4b5693
import java.util.*;
/**
public class TreeNode {
int val = 0;
TreeNode left = null;
TreeNode right = null;
public TreeNode(int val) {
this.val = val;
}
}*/
public class Solution {
public int nodeNum(TreeNode head) {
// 一些特殊情况的处理
if (null == head) {
return 0;
}
if (null == head.left && null == head.right) {
return 1;
}
int res = 0; // 定义一个整型变量,用于存放完全二叉树的节点个数
Queue<TreeNode> queue = new LinkedList<>();
TreeNode node = head;
queue.add(node);
while (!queue.isEmpty()) {
node = queue.poll();
res++;
if (null != node.left) {
queue.add(node.left);
}
if (null != node.right) {
queue.add(node.right);
}
}
return res;
}
}