Count Complete Tree Nodes

Medium#222tree nodes

You get the root of a complete binary tree: every level is full except maybe the last, and the last one is filled from the left. Count its nodes faster than by visiting each one. Our tree has 4 levels: the first three are full, and the last holds 5 nodes out of 8 — the answer is 12.

input
root: a complete binary tree, written as on LeetCode: its values level by level, left to right. Complete: every level is full but maybe the last one, whose nodes are all as far left as they go.
returns
The number of nodes in the tree; 0 for an empty tree. LeetCode wants it in less than O(n): without visiting every node.
constraints
  • 0 ≤ the number of nodes ≤ 1000
  • 0 ≤ Node.val ≤ 5 · 10⁴
  • the tree is complete
our 12 tests keep to them
examples
Open a test in the tests panel: it shows the input and the expected answer.
/**
 * Definition for a binary tree node.
 * function TreeNode(val, left, right) {
 *     this.val = (val===undefined ? 0 : val)
 *     this.left = (left===undefined ? null : left)
 *     this.right = (right===undefined ? null : right)
 * }
 */
/**
 * @param {TreeNode} root
 * @return {number}
 */
function countNodes(root) {

}
Ctrl ↵
format
reset

saved in this browser

12 tests · limit 3 s

Stuck?

See the solution run step by step on our example, then why it works and its complexity.

Watch the walkthrough →

Next: more depth-first search (dfs) problems

Pattern “Depth-first search (DFS)” →

The problem and its statement belong to LeetCode. Here are our own retelling, example and solution. Patterns Hero is not affiliated with LeetCode.