问题
I am trying to solve a binary search tree problem, but I can't pass all of the test cases. I need to return true if the tree is a binary search tree, otherwise, I need to return false. Can anyone tell me what I am doing wrong?
'''
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)
回答1:
You've a lot of redundant if
conditions in your code. You can simplify it like so:
def checkBST(root):
if root == None or (root.left == None and root.right == None):
return True
elif root.right == None:
return root.left.data < root.data and checkBST(root.left)
elif root.left == None:
return root.right.data >= root.data and checkBST(root.right)
return checkBST(root.left) and checkBST(root.right)
First, check for all the None
conditions. Short circuiting in python guarantees that if the first condition is False
, the second will not be evaluated. This allows you to write succinct statements such as return root.left.data < root.data and checkBST(root.left)
.
Finally, in the event that neither left nor right nodes are None
, do not call checkBST(root)
again. This leads to infinite recursion.
回答2:
So the reason you're not passing some of the tests is because you're only checking one level deep. For instance, if there is a tree
such that it has a root.left.right.data
> root.data
, then your code won't catch that. There is a good explanation here
But the gist is:
- Your code will pass this
- But it won't pass this Notice the right child of
2
>root.data
I think this solution solves it (sorry for answering a Python question with JS code, but I'm sure you'll get the idea):
function checkBST(root) {
let isBST = true;
let BSTUtil = r => {
let left, right
if(r.left) // Bottom out on the left side
left = BSTUtil(r.left)
if(r.right) // Bottom out on the right side
right = BSTUtil(r.right)
if(left > r.data) // Compare with parent
isBST = false
if(right < r.data) // Compare with parent
isBST = false
// Return MAX from branch
if(!left && !right)
return r.data
else if(!left)
return Math.max(right, r.data)
else
return Math.max(left, right, r.data)
}
BSTUtil(root)
return isBST;
}
Also, please don't use this code, it uses O(n)
space to solve the problem, and I'm sure I can find a more efficient solution if I spend some time on the question.
来源:https://stackoverflow.com/questions/44885472/check-if-a-tree-is-a-binary-search-tree-bst