4.5 Valid BST

For this problem, the first though came to my mind is the in-order traverse the BT, and keep check if it’s in ascending order. Another way to solve it by recursion.

    bool isValid(TreeNode* root, TreeNode* minNode, TreeNode* maxNode){
        if(!root)  return true;
        if((minNode && root->val<=minNode->val) || (maxNode && root->val >= maxNode->val)) return false;
        return isValid(root->left, minNode, root) && isValid(root->right, root, maxNode);
    }
    bool isValidBST(TreeNode *root) {
        // write your code here
        return isValid(root,NULL,NULL);
    }

你可能感兴趣的:(tree)