Determine whether a tree is a valid binary search tree.
A binary search tree is a tree with two children, left
and right
, and satisfies the constraint that the key in the left
the child must be less than or equal to the root and the key in the right
the child must be greater than or equal to the root.
Example:
Input: tree = [2,1,3]
Output: true
Approach
C++
#include <bits/stdc++.h>using namespace std;//struct for treenodestruct TreeNode{int data;TreeNode *left;TreeNode *right;TreeNode(int data){this->data = data;this->left = NULL;this->right = NULL;}};bool isValid(TreeNode *root, long long min1, long long max1){if (root == NULL)return true;if (root->data <= min1 || root->data >= max1)return false;return isValid(root->left, min1, root->data) &&isValid(root->right, root->data, max1);}bool isValidBST(TreeNode *root){return isValid(root, LLONG_MIN, LLONG_MAX);}int main(){TreeNode *root = new TreeNode(2);root->left = new TreeNode(1);root->right = new TreeNode(3);if (isValidBST(root))cout << "true";elsecout << "false";return 0;}
No comments:
Post a Comment