Check if all leaf nodes are at same level or not
Pattern: Depth, diameter and balance
Walk the tree remembering the depth. The first leaf found sets the level; every later leaf must be at that same depth.
No verified practice link yet. The guide below states the problem in full, so you can still solve it here.
The problem
Return whether all leaves are at the same depth. [1, 2, 3] is true; [10, 20, 30, 10, 15] is false. The catalogue has no practice link for this one. Trees in the examples are written in level order, with null for a missing child, as on LeetCode.
Think first
- What is a leaf?
- Which depth must every leaf have?
- Where does that depth come from?
Hints
Brute force, and why it fails
Collect every leaf's depth and compare: the same O(n), more memory.
The key insight
Fixing the depth at the first leaf and checking each later one stops at the first mismatch.
Dry run
| leafDepth | 2 |
|---|
[10, 20, 30, 10, 15]. The first leaf is 10 at depth 2.
Step 1 of 3
The plan
check(n, d): if null: true
if leaf: if leafDepth unset: leafDepth = d; return d == leafDepth
return check(left, d + 1) and check(right, d + 1)
Complexity
- Time
O(n)- Space
O(h)
One walk.
Edge cases
- Empty tree: true.
- One node: true.
- A node with one child is not a leaf.
I've built my logic, show the code
Java
class Solution {
private int leafDepth;
public boolean check(TreeNode root) {
leafDepth = -1; // not seen a leaf yet
return same(root, 0);
}
private boolean same(TreeNode n, int depth) {
if (n == null) return true;
if (n.left == null && n.right == null) {
if (leafDepth == -1) leafDepth = depth; // the first leaf sets the level
return depth == leafDepth;
}
return same(n.left, depth + 1) && same(n.right, depth + 1);
}
}C++
class Solution {
public:
int leafDepth;
bool check(TreeNode* root) {
leafDepth = -1; // not seen a leaf yet
return same(root, 0);
}
bool same(TreeNode* n, int depth) {
if (n == NULL) return true;
if (n->left == NULL && n->right == NULL) {
if (leafDepth == -1) leafDepth = depth; // the first leaf sets the level
return depth == leafDepth;
}
return same(n->left, depth + 1) && same(n->right, depth + 1);
}
};Python
class Solution:
def check(self, root) -> bool:
leaf_depth = -1 # not seen a leaf yet
def same(n, depth) -> bool:
nonlocal leaf_depth
if not n:
return True
if not n.left and not n.right:
if leaf_depth == -1:
leaf_depth = depth # the first leaf sets the level
return depth == leaf_depth
return same(n.left, depth + 1) and same(n.right, depth + 1)
return same(root, 0)Common mistakes
- Treating a node with one child as a leaf.
- Comparing with the tree's height instead of the first leaf.