I found many code to verify a valid binary tree, but I tried to creat a simple one, however it rise true all the time! Sorry I don't understand the recursion very well.
class TreeNode(object):
def __init__(self, x):
self.val = x
self.left = None
self.right = None
def is_BST():
if root:
return all(is_BST1(root))
def is_BST1(curnode):
if curnode.right:
if curnode.right.val>curnode.val:
is_BST1(curnode.right)
else:
yield False
if curnode.left:
if curnode.left.val<curnode.val:
is_BST1(curnode.left)
else:
yield False
else:
yield True
#tree creation code
print(is_BST)
Your main problem is that this line:
is_BST1(curnode.right)
only returns a generator, but does nothing with it. You should at least iterate on that generator:
...
if curnode.right:
if curnode.right.val>curnode.val:
# iterate on the generator built from right node
for i in is_BST1(curnode.right):
yield i
else:
...
and of course do the same for the left child...