LeetCode 222: Count Complete Tree Nodes
Given the root of a complete binary tree, return the number of the nodes in the tree.
A complete binary tree is a binary tree in which every level, except possibly the last, is completely filled, 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.
Input: root = [1,2,3,4,5,6]
Output: 6
Input: root = []
Output: 0
Q: Can the input tree be null? A: Yes, if the input tree is null, the output should be 0.
Q: What is the maximum height of the tree?
A: The height h
of the tree is such that the total number of nodes n
≤ 2^h - 1.
A complete binary tree has special properties which allow us to count nodes more efficiently than a simple traversal.
The following approach uses binary search and properties of a complete binary tree to count nodes efficiently.
# Definition for a binary tree node.
class TreeNode:
def __init__(self, val=0, left=None, right=None):
self.val = val
self.left = left
self.right = right
def countNodes(root: TreeNode) -> int:
if not root:
return 0
# Function to compute the depth of the leftmost path
def compute_depth(node):
depth = 0
while node:
node = node.left
depth += 1
return depth
left_depth = compute_depth(root.left)
right_depth = compute_depth(root.right)
if left_depth == right_depth:
return (1 << left_depth) + countNodes(root.right)
else:
return (1 << right_depth) + countNodes(root.left)
Got blindsided by a question you didn’t expect?
Spend too much time studying?
Or simply don’t have the time to go over all 3000 questions?