Given a binary tree to determine if it is a valid binary search tree.
Suppose a binary search tree having the following characteristics:
Left child node of the tree contains only less than the current node number.
Right subtree contain only greater than the number of nodes of the current node.
All left subtree and right subtree itself must also be binary search tree.
Example 1:
Example 2:
Low-level practice, preorder, see if ordered
1 # Definition for a binary tree node. 2 # class TreeNode: 3 # def __init__(self, x): 4 # self.val = x 5 # self.left = None 6 # self.right = None 7 8 class Solution: 9 def isValidBST(self, root: TreeNode) -> bool: 10 res_ = [] 11 stack = [] 12 while root or stack: 13 if root: 14 stack.append(root) 15 root = root.left 16 else: 17 root = stack.pop() 18 res_.append(root.val) 19 root = root.right 20 stack=res_.copy() 21 stack.sort() 22 if len(set(stack)) != len(stack): 23 return False 24 return stack== res_ 25 26
When execution: 68 ms, beat the 73.22% of users in all Python3 submission
Memory consumption: 16.8 MB, beat the 7.23% of users in all Python3 submission
Each time the current value and the upper and lower bounds are compared, the recursion process to its left and right subtrees:
1 class Solution: 2 def isValidBST(self, root): 3 """ 4 :type root: TreeNode 5 :rtype: bool 6 """ 7 def helper(node, lower = float('-inf'), upper = float('inf')): 8 if not node: 9 return True 10 11 val = node.val 12 if val <= lower or val >= upper: 13 return False 14 15 if not helper(node.right, val, upper): 16 return False 17 if not helper(node.left, lower, val): 18 return False 19 return True 20 21 return helper(root)
When execution: 76 ms, beat the 42.48% of users in all Python3 submission
Memory consumption: 16.2 MB, defeated with 39.06 percent of all Python3 submission