面试题21:如何判断二叉树是搜索二叉树BST?

时间:2023-03-08 20:49:32

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.
/**
* Definition for binary tree
* struct TreeNode {
* int val;
* TreeNode *left;
* TreeNode *right;
* TreeNode(int x) : val(x), left(NULL), right(NULL) {}
* };
*/
class Solution{
public:
TreeNode* pre = nullptr;
bool isValidBST(TreeNode* root){
if(root == nullptr) return true;
if(!isValidBST(root->left)) return false;
if(pre && root->val <= pre->val){
return false;
}
pre = root;
if(!isValidBST(root->right)) return false;
return true;
} };