Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- type
- BinarySearchTree = ref object
- Value: int
- LeftNode, RightNode: BinarySearchTree
- proc isValidBinarySearchTree(tree : BinarySearchTree, lowerBound : int, upperBound : int) : bool =
- if isNil(tree):
- return true
- elif tree.Value > upperBound or tree.Value < lowerBound:
- return false
- elif not isValidBinarySearchTree(tree.LeftNode, lowerBound, tree.Value):
- return false
- elif not isValidBinarySearchTree(tree.RightNode, tree.Value, upperBound):
- return false
- else:
- return true
- let example1 =
- BinarySearchTree(Value: 5,
- LeftNode: BinarySearchTree(Value: 1),
- RightNode: BinarySearchTree(Value: 4,
- LeftNode: BinarySearchTree(Value: 3),
- RightNode: BinarySearchTree(Value: 6)))
- let example2 =
- BinarySearchTree(Value: 5,
- LeftNode: BinarySearchTree(Value: 1),
- RightNode: BinarySearchTree(Value: 6,
- LeftNode: BinarySearchTree(Value: 4),
- RightNode: BinarySearchTree(Value: 7)))
- let example3 =
- BinarySearchTree(Value: 5,
- LeftNode: BinarySearchTree(Value: 1),
- RightNode: BinarySearchTree(Value: 6,
- LeftNode: BinarySearchTree(Value: 7),
- RightNode: BinarySearchTree(Value: 8)))
- let example4 =
- BinarySearchTree(Value: 5,
- LeftNode: BinarySearchTree(Value: 1),
- RightNode: BinarySearchTree(Value: 7,
- LeftNode: BinarySearchTree(Value: 6),
- RightNode: BinarySearchTree(Value: 8)))
- echo "Example1: ", isValidBinarySearchTree(example1, low(int), high(int))
- echo "Example2: ", isValidBinarySearchTree(example2, low(int), high(int))
- echo "Example3: ", isValidBinarySearchTree(example3, low(int), high(int))
- echo "Example4: ", isValidBinarySearchTree(example4, low(int), high(int))
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement