DEV Community

Abhishek Chaudhary
Abhishek Chaudhary

Posted on

Even Odd Tree

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).
  • For every odd-indexed level, all nodes at the level have even integer values in strictly decreasing order (from left to right).

Given the root of a binary tree, return true if the binary tree is Even-Odd, otherwise return false.

Example 1:

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:
Level 0: [1]
Level 1: [10,4]
Level 2: [3,7,9]
Level 3: [12,8,6,2]
Since levels 0 and 2 are all odd and increasing and levels 1 and 3 are all even and decreasing, the tree is Even-Odd.

Example 2:

Input: root = [5,4,2,3,3,7]
Output: false
Explanation: The node values on each level are:
Level 0: [5]
Level 1: [4,2]
Level 2: [3,3,7]
Node values in level 2 must be in strictly increasing order, so the tree is not Even-Odd.

Example 3:

Input: root = [5,9,1,3,5,7]
Output: false
Explanation: Node values in the level 1 should be even integers.

Constraints:

  • The number of nodes in the tree is in the range [1, 105].
  • 1 <= Node.val <= 106

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 levelOrder(self, root: Optional[TreeNode]) -> List[List[int]]:
        if not root:
            return []
        queue = [(root, 0)]
        levels = {}
        level = 0
        while len(queue) > 0:
            curr, level = queue.pop(0)
            levels[level] = levels.get(level, []) + [curr.val]
            if curr.left:
                queue.append((curr.left, level + 1))
            if curr.right:
                queue.append((curr.right, level + 1))
        return [levels[l] for l in range(level + 1)]

    def isOddAndIncreasing(self, arr):
        n = len(arr)
        for i in range(n - 1):
            if arr[i] >= arr[i + 1] or arr[i] % 2 == 0:
                return False
        if arr[-1] % 2 == 0:
            return False
        return True

    def isEvenAndDecreasing(self, arr):
        n = len(arr)
        for i in range(n - 1):
            if arr[i] <= arr[i + 1] or arr[i] % 2 == 1:
                return False
        if arr[-1] % 2 == 1:
            return False
        return True

    def isEvenOddTree(self, root: Optional[TreeNode]) -> bool:
        levels = self.levelOrder(root)
        for i, level in enumerate(levels):
            if i % 2 == 0 and not self.isOddAndIncreasing(level):
                return False
            elif i % 2 == 1 and not self.isEvenAndDecreasing(level):
                return False
        return True
Enter fullscreen mode Exit fullscreen mode

Hostinger image

Get n8n VPS hosting 3x cheaper than a cloud solution

Get fast, easy, secure n8n VPS hosting from $4.99/mo at Hostinger. Automate any workflow using a pre-installed n8n application and no-code customization.

Start now

Top comments (0)

Sentry image

See why 4M developers consider Sentry, “not bad.”

Fixing code doesn’t have to be the worst part of your day. Learn how Sentry can help.

Learn more

👋 Kindness is contagious

Please leave a ❤️ or a friendly comment on this post if you found it helpful!

Okay