PPractick

DSA interview question

Binary Tree Basics: Size, Height and Leaf Count

Easy · Data structures · Topics: tree, theory

The problem

A new engineer on a team that works with hierarchies (org charts, folder trees, decision trees) is asked to write the three most basic tree measurements. Size is the number of nodes. Height is the number of nodes on the longest root-to-leaf path (0 for an empty tree). Leaves is the number of nodes with no children. Each one follows the same recursive shape: the answer for a tree is built from the answers for its two subtrees, and the empty tree is the base case. That's the core idea behind almost every binary tree problem.

Example: [1, 2, 3, 4, 5, null, 6] → size 6, height 3, leaves 3.

Function signature

int size(TreeNode* root);
int height(TreeNode* root);   // nodes on the longest root-to-leaf path; 0 for an empty tree
int leaves(TreeNode* root);

Test cases

Input (level order)OutputExplanation
[1, 2, 3, 4, 5, null, 6]size=6 height=3 leaves=3Leaves 4, 5, 6
[1, 2, 3]size=3 height=2 leaves=2
[1, 2, null, 3, null, 4]size=4 height=4 leaves=1A left chain
[1]size=1 height=1 leaves=1The root is a leaf
[]size=0 height=0 leaves=0

(Confirm: height is counted in nodes, not edges; the input uses LeetCode's level-order format.)

How interviewers phrase it

Clarifying questions to ask

  1. Is height counted in nodes or edges? (Nodes here; the edge count is one less for a non-empty tree.)
  2. Is an empty tree allowed? (Yes: all three are 0.)
  3. Recursive or iterative?

Follow-ups to expect

  1. "What's the recursive pattern?"
  2. "Depth vs height?"
  3. "What are full, complete and perfect trees?"
  4. "Iterative versions?"
  5. "Complexity?"

Practise questions like this with a real engineer

On Practick another engineer interviews you live for 60 minutes on a question from this bank. They have the full interviewer guide beside the call: the expected answer to every follow-up, hints to give if you stall, and a scoring rubric. You get the model solution once the session settles. It is free: interview someone for an hour and you have earned your own.

Book a free mock interview

Related questions

All 474 dsa interview questions

DSA mock interviews · System design interview questions · Free mock interview practice · Browse interviewers · Sign in