# Definition for a binary tree node.
# class TreeNode(object):
# def __init__(self, x):
# self.val = x
# self.left = None
# self.right = None
class Solution(object):
def isValidBST(self, root):
"""
:type root: TreeNode
:rtype: bool
"""
if root==None:return True
return self.dfs(root,-99999999999,0x7fffffff)
def dfs(self,root,l,r):
v=root.val
if v<l or v>r:return False
if root.left==None and root.right==None:
return v<=r and v>=l
flag=0
if root.left!=None:
flag-=1
if self.dfs(root.left,l,v-1):flag+=1
if root.right!=None:
flag-=1
if self.dfs(root.right,v+1,r):flag+=1
return flag==0LeetCode-98-Validate Binary Search Tree dfs二叉树
最新推荐文章于 2019-04-18 10:41:33 发布
本文介绍了一种通过深度优先搜索(DFS)递归算法来验证给定二叉树是否为有效的二叉搜索树(BST)的方法。对于每个节点,算法确保其值在其父节点给定的范围内,并递归检查左右子树。
196

被折叠的 条评论
为什么被折叠?



