mirror of
https://github.com/TheAlgorithms/C
synced 2025-02-01 14:25:17 +03:00
feat: add Validate Binary Search Tree (#1153)
* add Validate Binary Search Tree * improve condition
This commit is contained in:
parent
defd82dda1
commit
435b4994ce
@ -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
24
leetcode/src/98.c
Normal 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);
|
||||
}
|
Loading…
x
Reference in New Issue
Block a user