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.
confused what "{1,#,2,3}"
means? > read more on how binary tree is serialized on OJ.
1. 用最大,最小指针在遍历二叉树时候判断是否有违反定义的节点
2和3都是用一个pre指针代表中序遍历的前一个节点,如果有pre->val >= cur->val则返回false
4. Morris 中序遍历,判断方式和2,3都一样
5. 用stack辅助做中序遍历,判断方式和2,3,4都一样
/**
* Definition for binary tree
* struct TreeNode {
* int val;
* TreeNode *left;
* TreeNode *right;
* TreeNode(int x) : val(x), left(NULL), right(NULL) {}
* };
*/
class Solution {
public:
bool isValidBST(TreeNode *root) {
// 1
//return isValidBST(root, NULL, NULL);
// 2
/*
TreeNode dummy(INT_MIN);
TreeNode *pre = &dummy;
return isValidBST(root, pre);
*/
// 3
/*
TreeNode *pre = NULL;
return isValidBST2(root, pre);
*/
// 4
TreeNode *pre = NULL;
TreeNode *cur = root;
bool ret = true;
while (cur != NULL) {
if (cur->left == NULL) {
if (pre != NULL && pre->val >= cur->val) ret = false;
pre = cur;
cur = cur->right;
} else {
TreeNode *l = cur->left;
while (l->right != NULL && l->right != cur) l = l->right;
if (l->right == NULL) {
l->right = cur;
cur = cur->left;
} else {
l->right = NULL;
if (pre != NULL && pre->val >= cur->val) ret = false;
pre = cur;
cur = cur->right;
}
}
}
return ret;
// 5
/*
TreeNode *pre = NULL;
TreeNode *cur = root;
stack<TreeNode*> tsk;
while (cur != NULL || !tsk.empty()) {
if (cur != NULL) {
tsk.push(cur);
cur = cur->left;
continue;
}
cur = tsk.top();
tsk.pop();
if (pre != NULL && pre->val >= cur->val) return false;
pre = cur;
cur = cur->right;
}
*/
}
private:
bool isValidBST(TreeNode *node, TreeNode *minNode, TreeNode *maxNode) {
if (node == NULL) return true;
if ((minNode != NULL && node->val <= minNode->val) || (maxNode != NULL && node->val >= maxNode->val)) return false;
return isValidBST(node->left, minNode, node) && isValidBST(node->right, node, maxNode);
}
bool isValidBST(TreeNode *node, TreeNode *&prevNode) {
if (node == NULL) return true;
if (!isValidBST(node->left, prevNode) || node->val <= prevNode->val) return false;
prevNode = node;
return isValidBST(node->right, prevNode);
}
bool isValidBST2(TreeNode *node, TreeNode *&prevNode) {
if (node == NULL) return true;
if (!isValidBST2(node->left, prevNode) || (prevNode != NULL && prevNode->val >= node->val)) return false;
prevNode = node;
return isValidBST2(node->right, prevNode);
}
};