MediumNo. 1609
Even Odd Tree — LeetCode 1609 Python Solution
- Pattern
- Tree Traversal
- Topics
- Tree, Breadth-First Search, Binary Tree
- Reading time
- 5 min
- Source
- leetcode.com
The problem
A binary tree is named Even-Odd if it meets the following conditions: The root of the binary tree is at level index 0, its children are at level index 1, their children are at level index 2, etc. For every even-indexed level, all nodes at the level have odd integer values in strictly increasing order (from left to right).
Example
- Input
- root = [1,10,4,3,null,7,9,12,8,6,null,null,2]
- Output
- true
- Explanation
- The node values on each level are:
Python solution
# 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
class Solution:
def isEvenOddTree(self, root: Optional[TreeNode]) -> bool:
even = 1
q = deque([root])
while q:
prev = 0 if even else inf
for _ in range(len(q)):
root = q.popleft()
if even and (root.val % 2 == 0 or prev >= root.val):
return False
if not even and (root.val % 2 == 1 or prev <= root.val):
return False
prev = root.val
if root.left:
q.append(root.left)
if root.right:
q.append(root.right)
even ^= 1
return TrueComplexity
- Time
- O(n)
- Space · auxiliary
- O(n)where n is the number of nodes in the binary tree
Pattern: Tree Traversal
Choose the order — preorder, inorder, postorder, level — and the problem solves itself. LeetCode 1609. Even Odd Tree is filed here because LeetCode tags it Tree and Binary Tree, which is the vocabulary this hub collects.
The tree traversal guide has the Python template for the pattern and the 225 LeetCode problems that use it.
Related problems
| No. | Problem | Difficulty |
|---|---|---|
| 0102 | Binary Tree Level Order Traversal | Medium |
| 0103 | Binary Tree Zigzag Level Order Traversal | Medium |
| 0107 | Binary Tree Level Order Traversal II | Medium |
| 0919 | Complete Binary Tree Inserter | Medium |
| 0958 | Check Completeness of a Binary Tree | Medium |
| 2471 | Minimum Number of Operations to Sort a Binary Tree by Level | Medium |
Frequently asked questions
- How hard is LeetCode 1609. Even Odd Tree?
LeetCode 1609. Even Odd Tree is rated Medium on LeetCode.
- What is the time complexity of LeetCode 1609. Even Odd Tree?
The Python solution on this page runs in O(n).
- What is the space complexity of LeetCode 1609. Even Odd Tree?
The Python solution on this page uses O(n), where n is the number of nodes in the binary tree auxiliary space.
- What topics does LeetCode 1609. Even Odd Tree cover?
LeetCode 1609. Even Odd Tree is tagged Tree, Breadth-First Search and Binary Tree on LeetCode.