1609. 奇偶树
为保证权益,题目请参考 1609. 奇偶树(From LeetCode).
解决方案1
Python
python
# 1609. 奇偶树
# https://leetcode-cn.com/problems/even-odd-tree/
# Definition for a binary tree node.
from typing import Optional
from collections import deque
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:
if root is None:
return True
que = deque()
que.append(root)
isEven = True
while len(que)!= 0:
if isEven:
next_que = deque()
que_max = -1
while len(que)!=0:
t = que.popleft()
if t.val %2 != 1:
return False
if t.val <= que_max:
return False
que_max = t.val
if t.left is not None:
next_que.append(t.left)
if t.right is not None:
next_que.append(t.right)
que = next_que
isEven = False
else:
next_que = deque()
que_min = 1000000000
while len(que) != 0:
t = que.popleft()
if t.val % 2 != 0:
return False
if t.val >= que_min:
return False
que_min = t.val
if t.left is not None:
next_que.append(t.left)
if t.right is not None:
next_que.append(t.right)
que = next_que
isEven = True
return True
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59