LintCode 97 验证二叉查找树
来源:互联网 发布:怎么找放单的淘宝商家 编辑:程序博客网 时间:2024/05/29 18:05
题目
http://www.lintcode.com/zh-cn/problem/validate-binary-search-tree/
给定一个二叉树,判断它是否是合法的二叉查找树(BST)
一棵BST定义为:
- 节点的左子树中的值要严格小于该节点的值。
- 节点的右子树中的值要严格大于该节点的值。
- 左右子树也必须是二叉查找树。
- 一个节点的树也是二叉查找树。
样例
一个例子:
2 / \1 4 / \ 3 5
上述这棵二叉树序列化为 {2,1,4,#,#,3,5}
.
方法:利用中序遍历是否递增来判断
C++代码
class Solution{public:void inorder(TreeNode *root ,vector<int> &res){if(root == NULL) return;inorder(root->left,res);res.push_back(root->val);inorder(root->right,res);}bool isValidBST(TreeNode*root){ vector<int> res; if(!root) return true;inorder(root,res);for(int i = 0;i <res.size()-1;i++){if(res[i] >= res[i+1])return false;} return true;}};
Python代码
def isValidBST(self, root): # write your code here if not root: return True return self._isValidBST(root.left,root.val,None)and \ self._isValidBST(root.right,None,root.val) def _isValidBST(self,root,lmax,rmin): if not root: return True if lmax and (root.val >=lmax): return False if rmin and (root.val <= rmin): return False return self._isValidBST(root.left,root.val,rmin)and\ self._isValidBST(root.right,lmax,root.val)
阅读全文
0 0
- LintCode 97 验证二叉查找树
- LintCode:验证二叉查找树
- LintCode : 验证二叉查找树
- Lintcode 验证二叉查找树
- 验证二叉查找树-LintCode
- 验证二叉查找树-LintCode
- lintcode-验证查找二叉树-95
- lintcode(95)验证二叉查找树
- LINTCODE —— 验证二叉查找树
- LintCode-分治-验证二叉查找树
- 验证二叉查找树—LintCode
- LintCode 95-验证二叉查找树
- lintcode validate-binary-search-tree 验证二叉查找树
- **[Lintcode]Validate Binary Search Tree 验证二叉查找树
- lintcode 二叉查找树总结
- lintcode二叉查找树总结
- 验证满二叉树-LintCode
- [LintCode]95.验证二叉查找树(二叉排序树/二叉搜索树) 中序遍历
- 30天自制操作系统------图形处理相关
- 将postgresql数据库内容导出至sqlite数据库
- 程序方法
- 快速排序及其改进
- Android
- LintCode 97 验证二叉查找树
- STL学习笔记-迭代器
- python中 Jupter的使用 notebook
- 各大巨头纷纷出手 数据中心市场硝烟弥漫
- java解析json格式数据
- 算法系列——Linked List Cycle II
- Cookie的路径和域
- SimpleDateFormat非线程安全
- 私有网络(腾讯云)