LeetCode 98. 验证二叉搜索树(递归)(迭代)

题目描述

给定一个二叉树,判断其是否是一个有效的二叉搜索树。
假设一个二叉搜索树具有如下特征:
节点的左子树只包含小于当前节点的数。
节点的右子树只包含大于当前节点的数。
所有左子树和右子树自身必须也是二叉搜索树。

在这里插入图片描述

思路

详见链接

代码

递归

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)

效果

在这里插入图片描述

发布了80 篇原创文章 · 获赞 239 · 访问量 7083

猜你喜欢

转载自blog.csdn.net/weixin_37763870/article/details/104336343