Leetcode 1731 Solution
This article provides solution to leetcode question 1731 (even-odd-tree)
Access this page by simply typing in "lcs 1731" in your browser address bar if you have bunnylol configured.
Leetcode Question Link
https://leetcode.com/problems/even-odd-tree
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:
level = 0
q = collections.deque()
q.append(root)
while q:
s = len(q)
if level % 2 == 0:
last_val = 0
else:
last_val = sys.maxsize
for _ in range(s):
child_node = q.popleft()
if level % 2 == child_node.val % 2:
return False
if level % 2 == 0:
if child_node.val <= last_val:
return False
else:
if child_node.val >= last_val:
return False
last_val = child_node.val
if child_node.left:
q.append(child_node.left)
if child_node.right:
q.append(child_node.right)
level += 1
return True