According to the definition, a Binary Tree must satisfy the following conditions:
1. The left subtree of a node contains only nodes with keys less than
the the node's key.
2. The right subtree of a node contains only nodes with keys greater than the node's key.
3. Both the left and right subtrees must also be binary search trees.
My code is returning True for the input [10 ,5, 15, #, #, 6, 20] but it's incorrect, it must return False.
The input follows a level order traversal, where '#' signifies a path terminator where no node exists below.
Here is the tree:
10
/ \
5 15
/ \
6 20
Here is my code :
# Definition for a binary tree node.
# class TreeNode(object):
# def __init__(self, x):
# self.val = x
# self.left = None
# self.right = None
def isValidBST(self, root)
"""
:type root: TreeNode
:rtype: bool
"""
if not root:
return True
else:
if root.left and root.right:
return root.left.val < root.val < root.right.val and \
self.isValidBST(root.left) and self.isValidBST(root.right)
elif root.left and not root.right:
return root.left.val < root.val and self.isValidBST(root.left)
elif root.right and not root.left:
return root.right.val > root.val and self.isValidBST(root.right)
else:
return True
(val left-subtree right-subtree)
? - Scott Hunter