Skip to content

Commit

Permalink
Update validate-binary-search-tree.cpp
Browse files Browse the repository at this point in the history
  • Loading branch information
kamyu104 authored Sep 8, 2016
1 parent ab7cd59 commit 04e3f90
Showing 1 changed file with 40 additions and 1 deletion.
41 changes: 40 additions & 1 deletion C++/validate-binary-search-tree.cpp
Original file line number Diff line number Diff line change
@@ -1,5 +1,5 @@
// Time: O(n)
// Space: O(h)
// Space: O(1)

/**
* Definition for a binary tree node.
Expand All @@ -10,7 +10,46 @@
* 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) {
Expand Down

0 comments on commit 04e3f90

Please sign in to comment.