思路一、
中序遍历,将树从大到小排序,然后一个循环比较前后大小,O(n)
//超出边界检验
bool checkOut(int v, vector<int> a) {
return v >= a.size();
}
//数组转化成树
bool arrayToTree(vector<int> arr, int i, TreeNode* &root) {
if(arr[i] != -1 && !checkOut(i, arr)) {
root = new TreeNode;
root->val = arr[i];
arrayToTree(arr, 2 * i + 1, root->left);
arrayToTree(arr, 2 * i + 2, root->right);
}
}
class Solution {
public:
bool check(vector<int> v) {
int i = 0;
bool count = true;
while(i < v.size() - 1) {
cout << v[i] << endl;
if(v[i] >= v[i + 1]) {
count = false;
break;
}
i++;
}
return count;
}
bool isValidBST(TreeNode* root) {
stack<TreeNode*> S;
TreeNode* temp = root;
vector<int> V;
while(!S.empty() || temp != NULL) {
while(temp != NULL) {
S.push(temp);
temp = temp->left;
}
if(!S.empty()) {
temp = S.top();
S.pop();
V.push_back(temp->val);
temp = temp->right;
}
}
return check(V);
}
};
思路二、
中序遍历+递归(转自LeetCode用户:缘)
class Solution{
public:
int* last = NULL;
bool isValidBST(TreeNode* root) {
if(root) {
if(!isValidBST(root->left)) return false;
if(last && *last >= root->val) return false;
last = &root->val;
if(!isValidBST(root->right)) return false;
return true;
} else return true;
}
};