验证具有重复关键字的二进制搜索树



给定一个以整数为键的二进制树,我需要测试它是否是一个正确的二进制搜索树。允许使用重复的整数。较小的元素在左边,较大的元素在右边,重复的元素总是在右边

import sys, threading
def IsBinarySearchTree(tree):
# Implement correct algorithm here
min = -sys.maxsize
max = sys.maxsize
def is_bst_until(idx_node,maxi,mini, is_left = False):
if idx_node == -1:
return True
node = tree[idx_node]
key = node[0]
idx_left = node[1]
idx_right = node[2]    
if (key>maxi) or (key<mini):
return False
if is_left:
if (key==mini):
return False
return (is_bst_until(idx_right, maxi, key)) and (is_bst_until(idx_left, key-1, mini, is_left=True))
if len(tree) == 0:
return True
return is_bst_until(0, max, min)

def main():
nodes = int(sys.stdin.readline().strip())
tree = []
for i in range(nodes):
tree.append(list(map(int, sys.stdin.readline().strip().split())))
if IsBinarySearchTree(tree):
print("CORRECT")
else:
print("INCORRECT")
threading.Thread(target=main).start()

输入格式。第一行包含顶点数量n。树的顶点编号从0到n−1。顶点0是根。接下来的n行包含关于顶点0、1、…、。。。,𝑛 −1按顺序排列。每行包含三个整数键,左和右

输出格式。如果给定的二进制树是正确的二进制搜索树,则输出一个单词"correct"。否则,输出一个单词"错误"。

示例:

3
2 1 2
2 -1 -1
3 -1 -1
#Incorrect
5
1 -1 1
2 -1 2
3 -1 3
4 -1 4
5 -1 -1
#Correct

我正在一次编程竞赛中解决这项任务。我没能满足所有的测试用例。我好像在什么地方搞错了。然而,我找不到被错误标记的测试用例。

如果你给我一个我的错误,我将不胜感激

import sys, threading
def IsBinarySearchTree(tree):
# Implement correct algorithm here
def is_bst_until(idx_node):
if idx_node == -1:
return True
node = tree[idx_node]
key = node[0]
idx_left = node[1]
idx_right = node[2]    
if(idx_left != -1 and key <= tree[idx_left][0]):
return False;
if(idx_right != -1 and key > tree[idx_right][0]):
return False;

return (is_bst_until(idx_right)) and (is_bst_until(idx_left))
if len(tree) == 0:
return True
return is_bst_until(0)

def main():
nodes = int(sys.stdin.readline().strip())
tree = []
for i in range(nodes):
tree.append(list(map(int, sys.stdin.readline().strip().split())))
if IsBinarySearchTree(tree):
print("CORRECT")
else:
print("INCORRECT")
threading.Thread(target=main).start()

最新更新