Ai
1 Star 2 Fork 5

LilithSangreal/LeetCode-Solutions

加入 Gitee
与超过 1200万 开发者一起发现、参与优秀开源项目,私有仓库也完全免费 :)
免费加入
文件
克隆/下载
validate-binary-search-tree.cpp 1.71 KB
一键复制 编辑 原始数据 按行查看 历史
kamyu 提交于 2016-09-08 23:54 +08:00 . Update validate-binary-search-tree.cpp
// Time: O(n)
// Space: O(1)
/**
* Definition for a binary tree node.
* struct TreeNode {
* int val;
* TreeNode *left;
* TreeNode *right;
* TreeNode(int x) : val(x), left(NULL), right(NULL) {}
* };
*/
// Morris Traversal
class Solution {
public:
bool isValidBST(TreeNode* root) {
TreeNode *prev = nullptr;
TreeNode *curr = root;
while (curr) {
if (!curr->left) {
if (prev && prev->val >= curr->val) {
return false;
}
prev = curr;
curr = curr->right;
} else {
TreeNode *node = curr->left;
while (node->right && node->right != curr) {
node = node->right;
}
if (!node->right) {
node->right = curr;
curr = curr->left;
} else {
if (prev && prev->val >= curr->val) {
return false;
}
prev = curr;
node->right = nullptr;
curr = curr->right;
}
}
}
return true;
}
};
// Time: O(n)
// Space: O(h)
class Solution2 {
public:
bool isValidBST(TreeNode* root) {
if (!root) {
return true;
}
if (!isValidBST(root->left)) {
return false;
}
if (last && last != root && last->val >= root->val) {
return false;
}
last = root;
if (!isValidBST(root->right)) {
return false;
}
return true;
}
private:
TreeNode *last = nullptr;
};
Loading...
马建仓 AI 助手
尝试更多
代码解读
代码找茬
代码优化
1
https://gitee.com/LilithSangreal/LeetCode-Solutions.git
git@gitee.com:LilithSangreal/LeetCode-Solutions.git
LilithSangreal
LeetCode-Solutions
LeetCode-Solutions
master

搜索帮助