leetcode Validate Binary Search Tree
2013-12-18 20:44
423 查看
中序遍历得到所有的顺序之后只需要比较相邻的两个结点是否有序就可以了!
/**
* Definition for binary tree
* struct TreeNode {
* int val;
* TreeNode *left;
* TreeNode *right;
* TreeNode(int x) : val(x), left(NULL), right(NULL) {}
* };
*/
class Solution {
public:
bool isValidBST(TreeNode *root) {
// IMPORTANT: Please reset any member data you declared, as
// the same Solution instance will be reused for each test case.
if(root==NULL)return true;
TreeNode * fa = NULL;
return solve(root,fa);
}
private:
bool solve(TreeNode *root,TreeNode * &fa){
if(root==NULL)return true;
bool ok = solve(root->left,fa);
if(!ok)return ok;
if(fa==NULL || fa->val<root->val){
fa = root;
return solve(root->right,fa);
}else return false;
}
};
/**
* Definition for binary tree
* struct TreeNode {
* int val;
* TreeNode *left;
* TreeNode *right;
* TreeNode(int x) : val(x), left(NULL), right(NULL) {}
* };
*/
class Solution {
public:
bool isValidBST(TreeNode *root) {
// IMPORTANT: Please reset any member data you declared, as
// the same Solution instance will be reused for each test case.
if(root==NULL)return true;
TreeNode * fa = NULL;
return solve(root,fa);
}
private:
bool solve(TreeNode *root,TreeNode * &fa){
if(root==NULL)return true;
bool ok = solve(root->left,fa);
if(!ok)return ok;
if(fa==NULL || fa->val<root->val){
fa = root;
return solve(root->right,fa);
}else return false;
}
};
相关文章推荐
- [LeetCode] Validate Binary Search Tree
- LeetCode: Validate Binary Search Tree [098]
- LeetCode--Validate Binary Search Tree
- [Leetcode]@python 98. Validate Binary Search Tree
- LeetCode 98 Validate Binary Search Tree(Python详解及实现)
- 【leetcode】Validate Binary Search Tree
- [LeetCode] Validate Binary Search Tree
- LeetCode No.98 Validate Binary Search Tree
- [Leetcode] Validate Binary Search Tree (Java)
- 【leetcode】Validate Binary Search Tree 题解三种思路
- [LeetCode] Validate Binary Search Tree
- 【Leetcode】【python】Validate Binary Search Tree
- Leetcode 98. Validate Binary Search Tree
- LeetCode Validate Binary Search Tree
- [leetcode]Validate Binary Search Tree @ Python
- LeetCode-validate-binary-search-tree
- LeetCode:Validate Binary Search Tree
- [leetcode]Validate Binary Search Tree
- LeetCode 98 — Validate Binary Search Tree(C++ Java Python)
- LeetCode: Validate Binary Search Tree