- tags: LeetCode
https://leetcode.com/problems/validate-binary-search-tree/
/**
* Definition for a binary tree node.
* struct TreeNode {
* int val;
* TreeNode *left;
* TreeNode *right;
* TreeNode() : val(0), left(nullptr), right(nullptr) {}
* TreeNode(int x) : val(x), left(nullptr), right(nullptr) {}
* TreeNode(int x, TreeNode *left, TreeNode *right) : val(x), left(left), right(right) {}
* };
*/
class Solution {
public:
bool isValidBST(TreeNode* root) {
if (root == nullptr || (root->left == nullptr && root->right == nullptr)) {
return true;
}
if (root->left != nullptr && root->right != nullptr) {
if (root->left->val >= root->val || root->right->val <= root->val) {
return false;
}
return isValidBST(root->left) && isValidBST(root->right);
}
if (root->left != nullptr) {
if (root->left->val >= root->val) {
return false;
}
return isValidBST(root->left);
}
if (root->right != nullptr) {
if (root->right->val <= root->val) {
return false;
}
return isValidBST(root->right) ;
}
return true;
}
};
无法处理子树元素大于上一层的问题。中序遍历排序:
/**
* Definition for a binary tree node.
* struct TreeNode {
* int val;
* TreeNode *left;
* TreeNode *right;
* TreeNode() : val(0), left(nullptr), right(nullptr) {}
* TreeNode(int x) : val(x), left(nullptr), right(nullptr) {}
* TreeNode(int x, TreeNode *left, TreeNode *right) : val(x), left(left), right(right) {}
* };
*/
class Solution {
public:
bool isValidBST(TreeNode* root) {
vector<int> ret;
stack<TreeNode*> st;
TreeNode* cur;
cur = root;
while (!st.empty() || cur != nullptr) {
while (cur != nullptr) {
st.push(cur);
cur = cur->left;
}
cur = st.top();
st.pop();
ret.push_back(cur->val);
cur = cur->right;
}
int prev = ret[0];
for (int i = 1; i < ret.size(); i++) {
auto r = ret[i];
if (r <= prev) {
return false;
}
prev = r;
}
return true;
}
};
可以去掉中间结果存数组:
/**
* Definition for a binary tree node.
* struct TreeNode {
* int val;
* TreeNode *left;
* TreeNode *right;
* TreeNode() : val(0), left(nullptr), right(nullptr) {}
* TreeNode(int x) : val(x), left(nullptr), right(nullptr) {}
* TreeNode(int x, TreeNode *left, TreeNode *right) : val(x), left(left), right(right) {}
* };
*/
class Solution {
public:
bool isValidBST(TreeNode* root) {
stack<TreeNode*> st;
TreeNode* cur = nullptr;
TreeNode* prev = nullptr;
cur = root;
while (!st.empty() || cur != nullptr) {
while (cur != nullptr) {
st.push(cur);
cur = cur->left;
}
cur = st.top();
st.pop();
if (prev != nullptr && cur->val <= prev->val) {
return false;
}
prev = cur;
cur = cur->right;
}
return true;
}
};
[2,1,3]
[5,1,4,null,null,3,6]
[2,2,2]
[5,4,6,null,null,3,7]