Count Complete Tree Nodes

Pattern: Depth, diameter and balance

medium

In a complete tree, measure the depth down the far left and down the far right. If they match, the tree is perfect and has 2^h - 1 nodes. Otherwise count the root and recurse into both children; one of them is always perfect, so the work is O(log² n).

The problem

Given a complete binary tree (every level full except possibly the last, which fills from the left), return the number of nodes, faster than visiting all of them. [1, 2, 3, 4, 5, 6] gives 6. Trees in the examples are written in level order, with null for a missing child, as on LeetCode.

Think first

  • How many nodes does a perfect tree of height h have?
  • How do you test for perfect cheaply?
  • Why is one of the two subtrees always perfect?

Hints

    Brute force, and why it fails

    Count every node: O(n).

    The key insight

    Perfect subtrees are counted with a formula, and only one path down the tree needs real work, giving O(log² n).

    Dry run

    left3
    right2

    Complete tree [1, 2, 3, 4, 5, 6]. Far-left depth 3, far-right depth 2: not perfect.

    Step 1 of 3

    The plan

    count(n): if null: 0
              l = far-left depth; r = far-right depth
              if l == r: return 2^l - 1
              return 1 + count(left) + count(right)
    

    Complexity

    Time
    O(log² n)
    Space
    O(log n)

    O(log n) levels of recursion, each measuring two O(log n) depths.

    Edge cases

    • Empty: 0.
    • Perfect tree: one formula.
    • Last level with one node.
    I've built my logic, show the code

    Java

    class Solution {
        public int countNodes(TreeNode root) {
            if (root == null) return 0;
            int left = 0, right = 0;
            for (TreeNode n = root; n != null; n = n.left) left++;    // the height down the far left
            for (TreeNode n = root; n != null; n = n.right) right++;  // and down the far right
            if (left == right) return (1 << left) - 1;                // the same: a perfect tree
            return 1 + countNodes(root.left) + countNodes(root.right);
        }
    }

    C++

    class Solution {
    public:
        int countNodes(TreeNode* root) {
            if (root == NULL) return 0;
            int left = 0, right = 0;
            for (TreeNode* n = root; n != NULL; n = n->left) left++;    // the height down the far left
            for (TreeNode* n = root; n != NULL; n = n->right) right++;  // and down the far right
            if (left == right) return (1 << left) - 1;                  // the same: a perfect tree
            return 1 + countNodes(root->left) + countNodes(root->right);
        }
    };

    Python

    class Solution:
        def countNodes(self, root) -> int:
            if not root:
                return 0
            left = right = 0
            n = root
            while n:                                # the height down the far left
                left, n = left + 1, n.left
            n = root
            while n:                                # and down the far right
                right, n = right + 1, n.right
            if left == right:
                return (1 << left) - 1              # the same: a perfect tree
            return 1 + self.countNodes(root.left) + self.countNodes(root.right)

    Common mistakes

    • Using this shortcut on a tree that is not complete.
    • Writing 2 << h instead of 1 << h.

    Similar problems