Check if all levels of two trees are anagrams or not
Pattern: Level order BFS
Walk both trees level by level together. Each pair of levels must have the same size and the same values in any order: sort both and compare. Any mismatch means false.
The problem
Return whether, at every level, the two trees hold the same values (in any order). [1, 3, 2, 5, 4] and
[1, 2, 3, 4, 5] give true. Two empty trees give true. Trees in the examples are written in level order, with null for a missing child, as on LeetCode.
Think first
- What must be equal level by level?
- How do you compare two lists ignoring order?
- What if the trees have different depths?
Hints
Brute force, and why it fails
Collect every level of both trees first, then compare: the same O(n log n), more memory.
The key insight
Walking both trees in lockstep stops at the first bad level and needs only one level of each in memory at a time.
Dry run
| match | yes |
|---|
Trees [1, 3, 2, 5, 4] and [1, 2, 3, 4, 5]. Level 0: [1] and [1].
Step 1 of 3
The plan
qa = [a]; qb = [b]
while qa or qb:
if sizes differ: return false
take one level from each; sort both; if different: return false
return true
Complexity
- Time
O(n log n)- Space
O(w)
Each level is sorted once.
Edge cases
- Both empty: true.
- One empty: false.
- Same values at different levels: false.
I've built my logic, show the code
Java
import java.util.*;
class Solution {
public boolean areAnagrams(TreeNode a, TreeNode b) {
Queue<TreeNode> qa = new ArrayDeque<>(), qb = new ArrayDeque<>();
if (a != null) qa.add(a);
if (b != null) qb.add(b);
while (!qa.isEmpty() || !qb.isEmpty()) {
if (qa.size() != qb.size()) return false; // levels of different sizes cannot match
List<Integer> la = nextLevel(qa), lb = nextLevel(qb);
Collections.sort(la);
Collections.sort(lb);
if (!la.equals(lb)) return false; // same values, any order
}
return true;
}
private List<Integer> nextLevel(Queue<TreeNode> q) {
List<Integer> level = new ArrayList<>();
int size = q.size();
for (int i = 0; i < size; i++) {
TreeNode node = q.poll();
level.add(node.val);
if (node.left != null) q.add(node.left);
if (node.right != null) q.add(node.right);
}
return level;
}
}C++
class Solution {
public:
bool areAnagrams(TreeNode* a, TreeNode* b) {
queue<TreeNode*> qa, qb;
if (a != NULL) qa.push(a);
if (b != NULL) qb.push(b);
while (!qa.empty() || !qb.empty()) {
if (qa.size() != qb.size()) return false; // levels of different sizes cannot match
vector<int> la = nextLevel(qa), lb = nextLevel(qb);
sort(la.begin(), la.end());
sort(lb.begin(), lb.end());
if (la != lb) return false; // same values, any order
}
return true;
}
vector<int> nextLevel(queue<TreeNode*>& q) {
vector<int> level;
int size = static_cast<int>(q.size());
for (int i = 0; i < size; i++) {
TreeNode* node = q.front();
q.pop();
level.push_back(node->val);
if (node->left != NULL) q.push(node->left);
if (node->right != NULL) q.push(node->right);
}
return level;
}
};Python
from collections import deque
class Solution:
def areAnagrams(self, a, b) -> bool:
qa, qb = deque([a] if a else []), deque([b] if b else [])
while qa or qb:
if len(qa) != len(qb):
return False # levels of different sizes cannot match
if sorted(self.next_level(qa)) != sorted(self.next_level(qb)):
return False # same values, any order
return True
def next_level(self, q: deque) -> list[int]:
level = []
for _ in range(len(q)):
node = q.popleft()
level.append(node.val)
if node.left:
q.append(node.left)
if node.right:
q.append(node.right)
return levelCommon mistakes
- Comparing whole trees instead of levels.
- Forgetting that the level sizes must match.