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.
OJ's Binary Tree Serialization:
The serialization of a binary tree follows a level order traversal, where '#' signifies a path terminator where no node exists below.
Here's an example:
1 / \ 2 3 / 4 \ 5
The above binary tree is serialized as"{1,2,3,#,#,4,#,#,5}".
/**
* Definition for binary tree
* struct TreeNode {
* int val;
* TreeNode *left;
* TreeNode *right;
* TreeNode(int x) : val(x), left(NULL), right(NULL) {}
* };
*/
class Solution {
public:
/*wrong:
if(NULL == root){
return true;
}else if(root->left && root->right){
if(!(root->left->val < root->val && root->val < root->right->val)){
return false;
}else{
return isValidBST(root->left)&&isValidBST(root->right);
}
}else if(!root->left && !root->right){
return true;
}else if(root->left){
if(root->left->val < root->val){
return isValidBST(root->left);
}else{
return false;
}
}else{
if(root->right->val > root->val){
return isValidBST(root->right);
}else{
return false;
}
}
*/
int val_arr[1000];
int index = 0;
void inorder_tra(TreeNode *root){
if(root==NULL){
return;
}
inorder_tra(root->left);
val_arr[index++] = root->val;
inorder_tra(root->right);
}
bool isValidBST(TreeNode *root) {
inorder_tra(root);
// printf("%d\n",index);
if(index == 1){
return true;
}else{
for(int i=1;i<index;++i){
if(val_arr[i-1]>=val_arr[i]){
return false;
}
}
return true;
}
}
};