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.
Because of the characteristic of the search tree, use inorder traversal on the tree is the best solution
/**
* Definition for a binary tree node.
* struct TreeNode {
* int val;
* TreeNode *left;
* TreeNode *right;
* TreeNode(int x) : val(x), left(NULL), right(NULL) {}
* };
*/
class Solution{
public:
bool isValidBST(TreeNode* root){
if(!root || !root->left && !root->right) return true;
//中序遍历二叉树
long long Maxval = -2147483648-1;
TreeNode* proot = root;
return isValidInorderTraversBST(root,Maxval);
}
bool isValidInorderTraversBST(TreeNode* root,long long &Maxval){
if(!root) return true;
bool flag1 = isValidInorderTraversBST(root->left,Maxval);
bool flag2 = root->val>Maxval;
if(flag2) Maxval = root->val;
else return false;
bool flag3 = isValidInorderTraversBST(root->right,Maxval);
return flag1&&flag2&&flag3;
}
};