我想解決二叉搜索樹問題,但我無法通過所有的測試用例。如果樹是二叉搜索樹,則需要返回true,否則,我需要返回false。誰能告訴我我做錯了什麼?樹是二叉搜索樹嗎?
'''
class node:
def __init__(self, data):
self.data = data
self.left = None
self.right = None
'''
def checkBST(root):
if root.left == None and root.right == None:
return True
if root == None:
return True
if root.left != None:
if root.left.data < root.data:
return True
else:
return False
if root.right != None:
if root.right.data > root.data:
return True
else:
return False
return chckBST(root.left) and chckBST(root) and chckBST(root.right)
哪些測試用例不是您傳遞的? –
爲什麼你再次調用'chckBST(root)',它應該是來自測試用例本身的第一次調用吧?我認爲遞歸調用應該只針對左側和右側 – Yazan