📅  最后修改于: 2023-12-03 14:54:56.018000             🧑  作者: Mango
二叉搜索树(Binary Search Tree,BST)是一种常见的树形数据结构,其中每个节点至多有两个子节点,且每个节点的左子节点的值小于该节点的值,每个节点的右子节点的值大于该节点的值。BST常常用于实现动态查找算法和排序算法。
class TreeNode:
def __init__(self, val=0, left=None, right=None):
self.val = val
self.left = left
self.right = right
def insert_node(root, val):
if root is None:
root = TreeNode(val)
elif val < root.val:
root.left = insert_node(root.left, val)
elif val > root.val:
root.right = insert_node(root.right, val)
return root
def delete_node(root, val):
if root is None:
return root
if val < root.val:
root.left = delete_node(root.left, val)
elif val > root.val:
root.right = delete_node(root.right, val)
else:
if root.left is None:
tmp = root.right
root = None
return tmp
elif root.right is None:
tmp = root.left
root = None
return tmp
tmp = find_min_node(root.right)
root.val = tmp.val
root.right = delete_node(root.right, tmp.val)
return root
def search_node(root, val):
if root is None or root.val == val:
return root
if root.val < val:
return search_node(root.right, val)
return search_node(root.left, val)
def pre_order(root):
if root:
print(root.val, end=" ")
pre_order(root.left)
pre_order(root.right)
def in_order(root):
if root:
in_order(root.left)
print(root.val, end=" ")
in_order(root.right)
def post_order(root):
if root:
post_order(root.left)
post_order(root.right)
print(root.val, end=" ")
给定一个二叉搜索树,判断其是否是一棵合法的BST。合法的BST定义为:无左子树的节点都比根节点小,无右子树的节点都比根节点大,并且其左右子树都是合法的BST。
输入:
2
/ \
1 3
输出: true
输入:
5
/ \
1 4
/ \
3 6
输出: false
题目中要求的是一棵合法的BST,因此我们可以利用BST的性质来判断。对于每个节点,其左子树的所有节点都应该小于该节点的值,其右子树的所有节点都应该大于该节点的值。我们可以利用递归来判断每个节点的左子树和右子树是否满足这个条件,如果满足,继续递归左右子树,如果不满足,返回false。
def is_valid_bst(root):
def helper(node, lower=float('-inf'), upper=float('inf')):
if node is None:
return True
val = node.val
if val <= lower or val >= upper:
return False
if not helper(node.right, val, upper):
return False
if not helper(node.left, lower, val):
return False
return True
return helper(root)