Binary Trees Depth first: return a value up
364. Count Complete Tree Nodes
You are given root, the root node of a complete binary tree. Return the number of nodes in the tree.
In a complete binary tree, every level is full except possibly the last one. The nodes on the last level sit as far left as they can, with no gaps between them. A tree whose last level is full is complete too, and so is an empty tree.
Counting every node is the easy part. Try to count them in less than O(n) time, where n is the number of nodes.
The examples write a tree level by level, from left to right, with null where a child is missing. So
root = [5,8,null,3] is the root 5 with a left child 8 and no right child, and 8 has a left child 3. The
missing children after the last node are left out.
Example 1
Input: root = [8, 3, 11, -4, 6, 9, 2, 5]
8Explanation: The first three levels are full and hold 1 + 2 + 4 = 7 nodes. The last level has one node, 5, at its far left. That makes 8 nodes.
Example 2
Input: root = []
0Explanation: The tree has no nodes.
Example 3
Input: root = [-3, -3, 0, -8, -3, 0, -8]
7Explanation: All three levels are full. Values repeat, but each node counts once.
Check your understanding
Work out the answer for this input before you write any code.
Constraints
0 ≤ number of nodes ≤ 105-109 ≤ Node.val ≤ 109- The tree is complete.
Clarifying questions
What you would ask an interviewer before writing any code.