-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy path110-binary_tree_is_bst.c
More file actions
37 lines (33 loc) · 948 Bytes
/
110-binary_tree_is_bst.c
File metadata and controls
37 lines (33 loc) · 948 Bytes
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
#include "binary_trees.h"
/**
* binary_tree_is_bst - checks if a binary tree is a valid Binary Search Tree
* @tree: a pointer to the root node of the tree to check
*
* Return: 1 if tree is a valid BST
* 0 otherwise
*/
int binary_tree_is_bst(const binary_tree_t *tree)
{
if (!tree)
return (0);
return (btib_helper(tree, INT_MIN, INT_MAX));
}
/**
* btib_helper - checks if a binary tree is a valid Binary Search Tree
* @tree: a pointer to the root node of the tree to check
* @min: Lower bound of checked nored
* @max: Upper bound of checked nodes
*
* Return: 1 if tree is a valid BST
* 0 otherwise
*/
int btib_helper(const binary_tree_t *tree, int min, int max)
{
if (!tree)
return (1);
if (tree->n < min || tree->n > max)
return (0);
return (btib_helper(tree->left, min, tree->n - 1) &&
btib_helper(tree->right, tree->n + 1, max));
/* -1 and +1 stem from "There must be no duplicate values" req */
}