#1609
Even Odd Tree
MediumTreeBreadth-First SearchBinary TreeBreadth-First SearchTree Traversal
Approaches
Brute ForceOptimal
Complexity Comparison
| Brute Force | Optimal Solution★ | |
|---|---|---|
| Time | O(n²) | O(n) |
| Space | O(1) | O(n) |
💡
Intuition
Time O(n)Space O(n)
We can still use a level-order traversal but check the conditions as we collect values, which avoids the need to store all values before validating them. This reduces unnecessary checks and improves efficiency.
⚙️
Algorithm
3 steps- 1Step 1: Use a queue for level-order traversal of the tree.
- 2Step 2: For each level, keep track of the previous value to ensure the current values meet the Even-Odd conditions.
- 3Step 3: Validate the values immediately as we traverse, returning false as soon as a condition fails.
solution.py25 lines
1from collections import deque
2
3def isEvenOddTree(root):
4 if not root:
5 return True
6 queue = deque([root])
7 level = 0
8 while queue:
9 level_size = len(queue)
10 prev_value = None
11 for _ in range(level_size):
12 node = queue.popleft()
13 if level % 2 == 0:
14 if node.val % 2 == 0 or (prev_value is not None and node.val <= prev_value):
15 return False
16 else:
17 if node.val % 2 != 0 or (prev_value is not None and node.val >= prev_value):
18 return False
19 prev_value = node.val
20 if node.left:
21 queue.append(node.left)
22 if node.right:
23 queue.append(node.right)
24 level += 1
25 return Trueℹ
Complexity note: The time complexity is O(n) because we traverse each node exactly once. The space complexity is O(n) due to the queue storing nodes at each level.
- 1Even-indexed levels must have odd values in increasing order.
- 2Odd-indexed levels must have even values in decreasing order.
Solutions and explanations are original Tejav content. Problem titles © LeetCode — use the LeetCode button above for the full problem statement.