• Hi Guys,

This is my first question here. My concern about my accepted answer is I feel it's not a elegant solution so I pasted it to get your opinion. Thanks in advance.

``````/**
* Definition for a binary tree node.
* struct TreeNode {
*     int val;
*     struct TreeNode *left;
*     struct TreeNode *right;
* };
*/

bool isAllNodesSmallerThan(struct TreeNode* root, int n){

if (root == NULL){
return true;
}

return (root->val < n && isAllNodesSmallerThan(root->left,n) && isAllNodesSmallerThan(root->right, n));
}

bool isAllNodesGreaterThan(struct TreeNode* root, int n){

if (root == NULL){
return true;
}

return (root->val > n && isAllNodesGreaterThan(root->left,n) && isAllNodesGreaterThan(root->right, n));
}
bool isValidBST(struct TreeNode* root) {

if (root == NULL){
return true;
}

if (isValidBST(root->left) && isValidBST(root->right)){

if (root->left != NULL && (root->left->val >= root->val || !isAllNodesSmallerThan(root->left, root->val) ) ){
return false;
}

if (root->right != NULL && (root->right->val <= root->val || !isAllNodesGreaterThan(root->right, root->val))){
return false;
}

return true;
}

return false;
}``````

• Look at other threads, you can improve the code by using inorder traverse and judge if pre-element is less than current value.

Looks like your connection to LeetCode Discuss was lost, please wait while we try to reconnect.