Given a binary tree, determine if it is a valid binary search tree (BST).
Input:
2
/ \
1 3
Output: true
5
/ \
1 4
/ \
3 6
Output: false
Explanation: The input is: [5,1,4,null,null,3,6]. The root node's value
is 5 but its right child's value is 4.
// Iteration
bool isValidBST(TreeNode* root) { // time: O(n); space: O(n)
if (!root) return true;
stack<TreeNode*> st;
TreeNode* prev = nullptr;
while (root || !st.empty()) {
while (root) {
st.push(root);
root = root->left;
}
root = st.top(); st.pop();
if (prev && root->val <= prev->val) return false;
prev = root;
root = root->right;
}
return true;
}
// Recursion
bool helper(TreeNode* node, TreeNode*& pre) {
if (!node) return true;
if (!helper(node->left, pre)) return false;
if (pre) {
if (node->val <= pre->val) return false;
}
pre = node;
return helper(node->right, pre);
}
bool isValidBST(TreeNode* root) { // time: O(n); space: O(n)
TreeNode *pre = nullptr;
return helper(root, pre);
}
// Morris Inorder Traversal
bool isValidBST(TreeNode* root) { // time: O(n); space: O(1)
if (!root) return true;
TreeNode *cur = root, *pre = nullptr, *parent = nullptr;
bool res = true;
while (cur) {
if (!cur->left) {
if (parent && parent->val >= cur->val) res = false;
parent = cur;
cur = cur->right;
} else {
pre = cur->left;
while (pre->right && pre->right != cur) pre = pre->right;
if (!pre->right) {
pre->right = cur;
cur = cur->left;
} else {
pre->right = nullptr;
if (parent->val >= cur->val) res = false;
parent = cur;
cur = cur->right;
}
}
}
return res;
}