blob: b646d4c3c909d5daea181b89ff0d2faea21ae2c7 (
plain)
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
|
# python3
import sys
def isBst(key, left, right):
if len(key) == 0:
return True
keyIndexStack = []
result = []
walkLeft = True
currentIndex = 0
keyIndexStack.append(currentIndex)
while len(keyIndexStack) != 0 or right[currentIndex] != -1:
if walkLeft:
if left[currentIndex] != -1:
if key[left[currentIndex]] >= key[currentIndex]:
return False
currentIndex = left[currentIndex]
keyIndexStack.append(currentIndex)
else:
i = keyIndexStack.pop()
if len(result) > 0:
if key[i] < result[-1]:
return False
result.append(key[i])
walkLeft = False
else:
if right[currentIndex] != -1:
if key[right[currentIndex]] < key[currentIndex]:
return False
currentIndex = right[currentIndex]
keyIndexStack.append(currentIndex)
walkLeft = True
else:
if len(keyIndexStack) != 0:
currentIndex = keyIndexStack.pop()
if len(result) > 0:
if key[currentIndex] <= result[-1]:
return False
result.append(key[currentIndex])
return True
if __name__ == '__main__':
n = int(sys.stdin.readline())
key = [0 for i in range(n)]
left = [0 for i in range(n)]
right = [0 for i in range(n)]
for i in range(n):
[a, b, c] = map(int, sys.stdin.readline().split())
key[i] = a
left[i] = b
right[i] = c
if isBst(key, left, right):
print("CORRECT")
else:
print("INCORRECT")
|