# 222. Count Complete Tree Nodes

Given the `root` of a **complete** binary tree, return the number of the nodes in the tree.

According to [**Wikipedia**](http://en.wikipedia.org/wiki/Binary_tree#Types_of_binary_trees), every level, except possibly the last, is completely filled in a complete binary tree, and all nodes in the last level are as far left as possible. It can have between `1` and `2h` nodes inclusive at the last level `h`.

Design an algorithm that runs in less than `O(n)` time complexity.

**Example 1:**

![](https://assets.leetcode.com/uploads/2021/01/14/complete.jpg)

<pre><code><strong>Input: root = [1,2,3,4,5,6]
</strong><strong>Output: 6
</strong></code></pre>

**Example 2:**

<pre><code><strong>Input: root = []
</strong><strong>Output: 0
</strong></code></pre>

***My Solutions:***

方法1：遍历所有节点

Time: O(n)

```java
/**
 * Definition for a binary tree node.
 * public class TreeNode {
 *     int val;
 *     TreeNode left;
 *     TreeNode right;
 *     TreeNode(int x) { val = x; }
 * }
 */
class Solution {
    public int countNodes(TreeNode root) {
         if (root == null) return 0;
         return 1 + countNodes(root.left) + countNodes(root.right);
    }
}
```

方法2: 利用complete树的性质，一定是从左往右填node。所以先找到树的高度，如果最后一层是满的，说明node的数量是2^height-1。不然则recursively找到最后一个满的位置

Time: O(lgn \* lgn)

```java
public int countNodes(TreeNode root) {
    if (root == null) return 0;
    TreeNode left = root, right = root;
    int height = 0;
    while (right != null) {
        left = left.left;
        right = right.right;
        height++;
    }
    
    // 这一层是满的
    if (left == null) return (int) Math.pow(2, height) - 1;
    else return 1 + countNodes(root.left) + countNodes(root.right);
}
```
