题目描述
给定一个二叉树,判断其是否是一个有效的二叉搜索树。
假设一个二叉搜索树具有如下特征:
节点的左子树只包含小于当前节点的数。
节点的右子树只包含大于当前节点的数。
所有左子树和右子树自身必须也是二叉搜索树。
思路
代码
递归
class TreeNode:
def __init__(self,x):
self.val = x
self.left = None
self.right = None
class Solution:
def isValidBST(self,root:TreeNode):
def isBST(root,min_val,max_val):
if root == None:
return True
if root.val >= max_val or root.val <= min_val:
return False
return isBST(root.left,min_val,root.val) and isBST(root.right,root.val,max_val)
return isBST(root,float("-inf"),float("inf"))
def stringToTreeNode(input):
input = input.strip()
input = input[1:-1]
if not input:
return None
inputValues = [s.strip() for s in input.split(',')]
root = TreeNode(int(inputValues[0]))
nodeQueue = [root]
front = 0
index = 1
while index < len(inputValues):
node = nodeQueue[front]
front = front + 1
item = inputValues[index]
index = index + 1
if item != "null":
leftNumber = int(item)
node.left = TreeNode(leftNumber)
nodeQueue.append(node.left)
if index >= len(inputValues):
break
item = inputValues[index]
index = index + 1
if item != "null":
rightNumber = int(item)
node.right = TreeNode(rightNumber)
nodeQueue.append(node.right)
return root
list = input("输入:")
b = stringToTreeNode(list)
test = Solution()
test.isValidBST(b)
class TreeNode:
def __init__(self,x):
self.val = x
self.left = None
self.right = None
class Solution:
def isValidBST(self,root:TreeNode):
if not root:
return True
stack = [(root,float("-inf"),float("inf"))]
while stack:
(root,min_val,max_val) = stack.pop()
if root:
val = root.val
if val <= min_val or val >= max_val:
return False
stack.append((root.right,val,max_val))
stack.append((root.left,min_val,val))
return True
def stringToTreeNode(input):
input = input.strip()
input = input[1:-1]
if not input:
return None
inputValues = [s.strip() for s in input.split(',')]
root = TreeNode(int(inputValues[0]))
nodeQueue = [root]
front = 0
index = 1
while index < len(inputValues):
node = nodeQueue[front]
front = front + 1
item = inputValues[index]
index = index + 1
if item != "null":
leftNumber = int(item)
node.left = TreeNode(leftNumber)
nodeQueue.append(node.left)
if index >= len(inputValues):
break
item = inputValues[index]
index = index + 1
if item != "null":
rightNumber = int(item)
node.right = TreeNode(rightNumber)
nodeQueue.append(node.right)
return root
list = input("输入:")
b = stringToTreeNode(list)
test = Solution()
test.isValidBST(b)