feat: add Validate Binary Search Tree (#1153)

* add Validate Binary Search Tree

* improve condition
This commit is contained in:
Alexander Pantyukhin 2022-11-26 04:54:41 +04:00 committed by GitHub
parent defd82dda1
commit 435b4994ce
No known key found for this signature in database
GPG Key ID: 4AEE18F83AFDEB23
2 changed files with 25 additions and 0 deletions

View File

@ -33,6 +33,7 @@
| 82 | [Remove Duplicates from Sorted List II](https://leetcode.com/problems/remove-duplicates-from-sorted-list-ii/) | [C](./src/82.c) | Medium |
| 83 | [Remove Duplicates from Sorted List](https://leetcode.com/problems/remove-duplicates-from-sorted-list/) | [C](./src/83.c) | Easy |
| 94 | [Binary Tree Inorder Traversal](https://leetcode.com/problems/binary-tree-inorder-traversal/) | [C](./src/94.c) | Medium |
| 98 | [Validate Binary Search Tree](https://leetcode.com/problems/validate-binary-search-tree/) | [C](./src/98.c) | Medium |
| 101 | [Symmetric Tree](https://leetcode.com/problems/symmetric-tree/) | [C](./src/101.c) | Easy |
| 104 | [Maximum Depth of Binary Tree](https://leetcode.com/problems/maximum-depth-of-binary-tree/) | [C](./src/104.c) | Easy |
| 108 | [Convert Sorted Array to Binary Search Tree](https://leetcode.com/problems/convert-sorted-array-to-binary-search-tree/) | [C](./src/108.c) | Easy |

24
leetcode/src/98.c Normal file
View File

@ -0,0 +1,24 @@
/**
* Definition for a binary tree node.
* struct TreeNode {
* int val;
* struct TreeNode *left;
* struct TreeNode *right;
* };
*/
// Depth first search approach.
// Runtime: O(n)
// Space: O(1)
bool checkIsBst(struct TreeNode* node, bool leftBoundInf, int leftBound, bool rightBoundInf, int rightBound){
return
(node == NULL)
|| (leftBoundInf || node->val > leftBound)
&& (rightBoundInf || node->val < rightBound)
&& checkIsBst(node->left, leftBoundInf, leftBound, false, node->val)
&& checkIsBst(node->right, false, node->val, rightBoundInf, rightBound);
}
bool isValidBST(struct TreeNode* root){
return checkIsBst(root, true, INT_MIN, true, INT_MAX);
}