Leetcode: Validate Binary Search Tree
1 min readDec 26, 2016
The inorder traversal of a binary search tree should be a sorted array. We can solve this problem using this concept. To know more about how inorder traversal is obtained please visit the corresponding blog post.
- Get the inorder traversal of the given BST as a list
- Iterate through the list and check if it is sorted
Remarks:
- O(n) time complexity, n units for getting the inorder traversal and another n units for checking if the order is sorted
- O(n) space complexity, for storing the inorder traversal output
# Definition for a binary tree node.
# class TreeNode(object):
# def __init__(self, x):
# self.val = x
# self.left = None
# self.right = Noneclass Solution(object):
def isValidBST(self, root):
"""
:type root: TreeNode
:rtype: bool
"""
inorder = self.inorderTraversal(root)
for i in range(1, len(inorder)):
if inorder[i - 1] >= inorder[i]:
return False
return True def inorderTraversal(self, root):
return self.inorderTraversal(root.left) + [root.val] + self.inorderTraversal(root.right) if root else []