98 Validate Binary Search Tree
来源:互联网 发布:淘宝客平台源码 编辑:程序博客网 时间:2024/05/20 04:09
# 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
"""
return self.isValidBst(root,-2147483649,2147483648)
def isValidBst(self,root,minVal,maxVal):
if not root :
return True
if root.val >=maxVal or root.val <=minVal:
return False
return self.isValidBst(root.left,minVal,root.val) and self.isValidBst(root.right,root.val,maxVal)
题意:验证所给二叉树是不是一颗搜索树
解题:用递归实现dfs的方法
1.设计叶子节点的出来方式
2.使用一个方法给定3个输入值的顺序
3.设计一个错误的出口
4.考虑初始值的最大和最小范围
检查右子树与根节点的关系用根做最小值,检查左子树与根的关系用根做最大值
discuss排名第一的答案:
class Solution(object):
prev = None
def isValidBST(self, root):
"""
:type root: TreeNode
:rtype: bool
"""
return self.validate(root)
def validate(self,node):
if not node :
return True
if not self.validate(node.left):
return False
if self.prev!=None and self.prev.val >= node.val:
return False
self.prev = node
return self.validate(node.right)
利用一个全局的变量来记录上一个访问过的节点
- 98Validate Binary Search Tree
- 98 Validate Binary Search Tree
- 98 Validate Binary Search Tree
- 98 Validate Binary Search Tree
- 98 Validate Binary Search Tree
- Validate Binary Search Tree
- Validate Binary Search Tree
- Validate Binary Search Tree
- Validate Binary Search Tree
- Validate Binary Search Tree
- Validate Binary Search Tree
- Validate Binary Search Tree
- Validate Binary Search Tree
- Validate Binary Search Tree
- Validate Binary Search Tree
- Validate Binary Search Tree
- Validate Binary Search Tree
- Validate Binary Search Tree
- 软件无线电 SDR LTE平台简介---OAI、srsLTE、OpenLTE与Amarisoft
- Android 版本更新,安装
- Invalid argument supplied for foreach()
- for ... of循环和for ... in循环的区别
- Map和set
- 98 Validate Binary Search Tree
- Error: Can't set headers after they are sent to the client
- 全面介绍Android Studio中Git 的使用(一)
- Linux下挂后台运行python脚本
- Airbnb 的核心日志系统架构及主要系统模块的设计之道
- vtkPolyData 的空间变换(平移、旋转、缩放)
- 初使用Hbuider如何新建web项目
- editText软键盘,挤屏,关闭
- jdbc基础操作