题目链接
法一(普通二叉树DFS)
public int countNodes(TreeNode root) {
if (root == null) {
return 0;
}
return countNodes(root.left) + countNodes(root.right) + 1;
}
法二(普通二叉树BFS)
public int countNodes_2(TreeNode root) {
if (root == null) {
return 0;
}
Queue<TreeNode> queue = new LinkedList<>();
queue.offer(root);
int cnt = 0;
while (!queue.isEmpty()) {
int size = queue.size();
cnt += size;
while (size-- > 0) {
TreeNode cur = queue.poll();
if (cur.left != null) queue.offer(cur.left);
if (cur.right != null) queue.offer(cur.right);
}
}
return cnt;
}
法三(利用完全二叉树性质DFS)
public int countNodes_3(TreeNode root) {
if (root == null) {
return 0;
}
TreeNode left = root.left, right = root.right;
int leftDepth = 0, rightDepth = 0;
while (left != null) {
left = left.left;
leftDepth++;
}
while (right != null) {
right = right.right;
rightDepth++;
}
if (leftDepth == rightDepth) {
return (2 << leftDepth) - 1;
}
return countNodes(root.left) + countNodes(root.right) + 1;
}
本地测试
lay.showTitle(222);
Solution222 sol222 = new Solution222();
List<Integer> arr222 = Arrays.asList(7, 3, 15, null, null, 9, 20);
TreeNode root222 = treeOpt.createTreeByLayerOrder(arr222);
treeOpt.layerOrder(root222);
System.out.println(sol222.countNodes(root222));
System.out.println(sol222.countNodes_2(root222));
System.out.println(sol222.countNodes_3(root222));