[leetcode] Validate Binary Search Tree
2015-06-10 10:40
337 查看
Validate Binary Search Tree
Given a binary tree, determine if it is a valid binary search tree (BST).Assume a BST is defined as follows:
The left subtree of a node contains only nodes with keys less than the node's key.
The right subtree of a node contains only nodes with keys greater than the node's key.
Both the left and right subtrees must also be binary search trees.
confused what
"{1,#,2,3}"means? > read more on how binary tree is serialized on OJ.
分析:二叉搜索树的中序遍历是从小到大排列的。
/** * Definition for a binary tree node. * struct TreeNode { * int val; * TreeNode *left; * TreeNode *right; * TreeNode(int x) : val(x), left(NULL), right(NULL) {} * }; */ class Solution { private: int pre; vector<int> vec; public: Solution():pre(LONG_MIN) {} bool isValidBST(TreeNode* root) { vec.clear(); if(root == NULL) return true; if(root->left==NULL && root->right==NULL) return true; isValid(root); for(int i=1; i<vec.size(); i++) if(vec[i-1] >= vec[i]) return false; return true; } void isValid(TreeNode* root) { if(root) { isValid(root->left); vec.push_back(root->val); isValid(root->right); } } };
方法二:设置上下界
class Solution { public: bool isValidBST(TreeNode* root) { if(root == NULL) return true; if(root->left==NULL && root->right==NULL) return true; return isValid(root, LONG_MIN, LONG_MAX); } bool isValid(TreeNode* root, int min, int max) { if(root==NULL) return true; if(root->val <= min || root->val >= max) return false; return isValid(root->left, min, root->val) && isValid(root->right, root->val, max); } };
相关文章推荐
- hdoj 2 括号配对问题【数组模拟实现+STL实现】
- SVN 解决Unable to connect to a repository at URL 禁止访问 (forbidden)
- C#中实现判断某个类是否实现了某个接口
- 行业百科知识--Github
- DELPHI字符串、数组操作函数(转)
- MR环境配置
- (DBA之路【五】)关于锁的故事
- android中的category
- AIX查看CPU及内存参数
- HDU-1042-N!(Java大法好 && HDU大数水题)
- hibernate注意
- 依赖冲突-cglib和asm
- caffe, torch, theano
- 关于史考特证券(scottrade Inc)资金转出的手续费问题
- Matrix相关
- 程序员的量化交易之路(32)--Cointrade之Portfolio组合(19)
- 泛型和非泛型
- (ACM学习笔记)POJ 1160中四边形不等式的应用
- 关于Spring中的<context:annotation-config/>配置
- 块设备--blk.h/hd.c/ll_rw_blk.c源码分析