[LeetCode in Python] 98 (M) validate binary search tree 验证二叉搜索树
2021-02-09 19:16
标签:sel one ble 大于 特征 binary tree 代码 题目 https://leetcode-cn.com/problems/validate-binary-search-tree/ 给定一个二叉树,判断其是否是一个有效的二叉搜索树。 节点的左子树只包含小于当前节点的数。 示例?1: 输入: 输出: true 示例?2: 输入: 输出: false 解释: 输入为: [5,1,4,null,null,3,6]。 [LeetCode in Python] 98 (M) validate binary search tree 验证二叉搜索树 标签:sel one ble 大于 特征 binary tree 代码 题目 原文地址:https://www.cnblogs.com/journeyonmyway/p/12749395.html题目
假设一个二叉搜索树具有如下特征:
节点的右子树只包含大于当前节点的数。
所有左子树和右子树自身必须也是二叉搜索树。 2
/ 1 3
5
/ 1 4
? / ? 3 6
? 根节点的值为 5 ,但是其右子节点值为 4 。解题思路
代码
# Definition for a binary tree node.
# class TreeNode:
# def __init__(self, x):
# self.val = x
# self.left = None
# self.right = None
class Solution:
def isValidBST(self, root: TreeNode) -> bool:
def dfs(node, min_node, max_node):
if not node: return True
# - check node
if min_node and (node.val = max_node.val): return False
# - dfs left and right branch
if node.left and (not dfs(node.left, min_node, node)): return False
if node.right and (not dfs(node.right, node, max_node)): return False
return True
return dfs(root, None, None)
文章标题:[LeetCode in Python] 98 (M) validate binary search tree 验证二叉搜索树
文章链接:http://soscw.com/index.php/essay/53219.html