LeetCode || Validate Binary Search Tree
2015-07-29 20:06
555 查看
Validate Binary Search Tree
题目链接 耗时:16ms
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 {
public:
//中序遍历的实现
void GetInOrder(TreeNode* root, vector<int>& v)
{
if(root == NULL)
return;
if(root->left!=NULL)
{
GetInOrder(root->left, v);
}
v.push_back(root->val);
if(root->right != NULL)
GetInOrder(root->right, v);
}
bool isValidBST(TreeNode* root) {
//错误的做法:运用递归来实现遍历,避免出现【10, 5, 15, null, null, 6, 20】此类树的结构从而出现错误的判断。
//正确的做法: 利用中序遍历得到的是排好序的结构。
vector<int> v;
GetInOrder(root, v);
for(int i = 1;i<v.size();i++)
{
if(v[i] <= v[i-1])
return false;
}
return true;
}
};
相关文章推荐
- Detecting diabetic retinopathy in eye images
- POJ 1679 The Unique MST
- c++ 11 新特性
- 18.4Sum (Map)
- #1128 : 二分·二分查找
- hls 类型
- HDOJ 1863 畅通工程(最小生成树--kruskal)
- 压缩感知在目标跟踪的应用
- 压缩感知在目标跟踪的应用
- 开启mediawiki其他非默认功能
- Windows突然不能访问某些网址
- Python 用 os.walk 遍历目录
- 归并排序
- Log图文详解(Log.v,Log.d,Log.i,Log.w,Log.e)(转)
- oracle bi publisher报表插入图片
- 把握linux内核设计思想(六):内核时钟中断
- CUDA 中解决 critical section 的一些策略
- Android四大组件
- URI和URL的区别
- ios UI 适配布局相关文章