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.
/**
* 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:
bool isValidBST(TreeNode* root) {
// v.size() == 0
if (root == nullptr) return true;
vector<int> v;
read(root, v);
size_t i = 1;
for(; i != v.size(); ++i) {
if (v[i] <= v[i - 1])
break;
}
return i == v.size();
}
// 遍历
void read(TreeNode* root, vector<int>& v) {
if (root == nullptr) return;
read(root->left, v);
v.push_back(root->val);
read(root->right, v);
}
};
/**
* 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:
bool isValidBST(TreeNode* root) {
// v.size() == 0
if (root == nullptr) return true;
vector<long> v(1, long(INT_MIN) - 1);
return read(root, v);
}
// 遍历
bool read(TreeNode* root, vector<long>& v) {
if (root == nullptr) return true;
if (read(root->left, v) == false) return false;
if (root-> val <= v[v.size() - 1]) return false;
v.push_back(root->val);
return read(root->right, v);
}
};
参考后
/**
* 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:
bool isValidBST(TreeNode* root) {
TreeNode* p = root;
stack<TreeNode*> s;
long lastVal = long(INT_MIN) - 1;
while (p != nullptr || !s.empty()) {
if (p != nullptr) {
s.push(p);
p = p->left;
}
else {
p = s.top();
s.pop();
if (lastVal >= p->val) return false;
lastVal = p->val;
p = p->right;
}
}
return true;
}
};