LeetCode/solutions/98. Validate Binary Search Tree.md
2019-04-22 00:11:37 +08:00

64 lines
2.2 KiB
Markdown
Raw Blame History

This file contains ambiguous Unicode characters

This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.

# [98. Validate Binary Search Tree](https://leetcode.com/problems/validate-binary-search-tree/)
# 思路
## 思路一
根据BST的定义。二叉搜索树或者是一棵空树或者是具有下列性质的二叉树
* 若它的左子树不空,则左子树上**所有**结点的值均小于它的根结点的值;
* 若它的右子树不空,则右子树上**所有**结点的值均大于它的根结点的值;
* 它的左、右子树也分别为二叉排序树。
> 注意“所有”。
实现过程中,为了检查左子树(已经是一个二叉搜索树)上**所有**结点的值是否均小于它的根结点的值,我们可以检查左子树上的最大值(一直沿右路下降即可)小于它的根结点的值即可。右子树亦然。
## 思路二
还可以检验中序遍历序列是否是严格递增的来判断是否是BST。
我们可以用一个全局变量pre记录上一个中序遍历节点值当前节点值必须大于pre才行。所以pre的初始值为`INT_MIN-1`所以为了防止溢出pre应该是long long型
# C++
## 思路一
``` C++
class Solution {
public:
bool isValidBST(TreeNode* root) {
if(root == NULL) return true;
if(root -> left != NULL){
if(!isValidBST(root -> left)) return false;
TreeNode* p = root -> left;
while(p -> right) p = p -> right; // 沿右路下降
if(root -> val <= p -> val) return false;
}
if(root -> right != NULL){
if(!isValidBST(root -> right)) return false;
TreeNode* p = root -> right;
while(p -> left) p = p -> left; // 沿左路下降
if(root -> val >= p -> val ) return false;
}
return true;
}
};
```
## 思路二
``` C++
class Solution {
private:
long long pre = (long long)INT_MIN - 1;
bool inorder(TreeNode *root){
if(root == NULL) return true;
if(!inorder(root -> left)) return false;
if(root -> val <= pre) return false;
pre = root -> val;
if(!inorder(root -> right)) return false;
return true;
}
public:
bool isValidBST(TreeNode* root) {
pre = (long long)INT_MIN - 1;
return inorder(root);
}
};
```