222. Count Complete Tree Nodes

1. Description

Given the root of a complete binary tree, return the number of the nodes in the tree.
According to Wikipedia, 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 $2^h$ nodes inclusive at the last level h.
Design an algorithm that runs in less than O(n) time complexity.

2. Example

Example 1

Example 1
Input: root = [1,2,3,4,5,6]
Output: 6

Example 2

Input: root = []
Output: 0

Example 3

Input: root = [1]
Output: 1

3. Constraints

  • The number of nodes in the tree is in the range [0, 5 * $10^4$].
  • 0 <= Node.val <= 5 * $10^4$
  • The tree is guaranteed to be complete.

4. Solutions

n is the number of nodes in root
Time complexity: O($log^2n$)
Space complexity: O(1)

class Solution {
public:
    int countNodes(TreeNode *root) {
        if (root == nullptr) {
            return 0;
        }

        int height = 0;
        for (auto iter = root; iter != nullptr; iter = iter->left) {
            ++height;
        }

        if (height == 1) {
            return 1;
        }

        int last_layer_count = 1 << (height - 1);
        int left = 0, right = last_layer_count;
        while (left < right) {
            int middle = left + (right - left) / 2;

            auto iter = root;
            for (int i = 0, bit = 1 << (height - 2); i < height - 1; ++i) {
                if ((bit & middle) == 0) {
                    iter = iter->left;
                } else {
                    iter = iter->right;
                }

                bit >>= 1;
            }

            if (iter == nullptr) {
                right = middle;
            } else {
                left = middle + 1;
            }
        }

        return (1 << (height - 1)) - 1 + left;
    }
};
comments powered by Disqus