LeetCode 98. 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.
Example 1:
Input:
2
/ \
1 3
Output: true
Example 2:
5
/ \
1 4
/ \
3 6
Output: false
Explanation: The input is: [5,1,4,null,null,3,6]. The root node's value
is 5 but its right child's value is 4.
题目理解:
与以往的建立二叉搜索树不同,这次是已经建立好的二叉搜索树,凡是树都要先想想递归方法解决问题,以下是我的思路历程:
1.首先按照建立二叉搜索树的思路的进行方法判断,就是小于根结点进入左子树,大于根结点进入右子树,其余情况返回false,把每次的结果于起来得到最终结果。但是这样做无法判断子树的儿子们与子树的父亲之间的关系,就是说在这样的情况下无法判断,针对出错的样例我修补了一番,但是还是无法解决问题,后面参考优秀代码有了思路~
2.在黔驴技穷时,准备研究优秀代码,然后突然间看到了preOrder,瞬间就有了思路,因为如果是二叉搜索树,那么按照前序遍历后得到的顺序就一定是升序排好的,故只要得到所给树的前序遍历结果,再将其重新排序,最后比较排序后和原始结果是否相同就可以进行判断了。这里注意一点,重新排序后的结果如果有两个相同值那么就会直接返回false。
/**
* 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:
vector<int> tmp;
void preOrder(TreeNode* root){
if(root->left!=NULL) preOrder(root->left);
tmp.push_back(root->val);
if(root->right!=NULL) preOrder(root->right);
}
bool isValidBST(TreeNode* root) {
if (root == NULL) return true;
if(root->left == NULL && root->right == NULL) return true;
preOrder(root);
vector<int> sorted(tmp);
sort(sorted.begin(),sorted.end());
for(int i=0;i<sorted.size()-1;i++){
if(sorted[i] == sorted[i+1]){
return false;
}
}
if(sorted==tmp){
return true;
}else{
return false;
}
}
};
3.在实现了自己的思路后又看了优秀代码,想法1中没能实现的问题是因为每次递归没有保留迭代过程中的最大和最小值。但是总感觉不是特别清晰,怎么办,只能先学习着咯,慢慢变成自己的东西。。。
class Solution {
public:
bool judge(TreeNode* root,long long int minV,long long int maxV){
if(!root) return true;
if(root->val >= maxV || root->val <= minV) return false;
if(!judge(root->left,minV,min(maxV,(long long int)root->val))) return false;
return judge(root->right,max(minV,(long long int)root->val),maxV);
}
bool isValidBST(TreeNode* root) {
if (root == NULL) return true;
if(root->left == NULL && root->right == NULL) return true;
return judge(root,LONG_MIN,LONG_MAX);
}
};
加加油///