-
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
93 lines (90 loc) · 2.19 KB
/
110-binary_tree_is_bst.c
File metadata and controls
93 lines (90 loc) · 2.19 KB
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
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
#include "binary_trees.h"
/**
* check_sub_tree_Left - check if all nodes are smaller than
* the root specified
* @node: node in the tree to verify condition
* @max: value to compare
* Return: 1 if all nodes are smaller or equal or 0 if not
*/
int check_sub_tree_Left(const binary_tree_t *node, int max)
{
int left = 0, right = 0;
if (node == NULL)
{
return (1);
}
else
{
if (node->n >= max)
return (0);
left = check_sub_tree_Left(node->left, max);
right = check_sub_tree_Left(node->right, max);
if (left == right && left == 1)
return (1);
return (0);
}
}
/**
* check_sub_tree_Right - check if all the nodes are bigger than the
* root specified
* @node: node in the tree to verify condition
* @min: value to compare
* Return: 1 if all is bigger or equal or 0 if not
*/
int check_sub_tree_Right(const binary_tree_t *node, int min)
{
int left = 0, right = 0;
if (node == NULL)
{
return (1);
}
else
{
if (node->n <= min)
return (0);
left = check_sub_tree_Right(node->left, min);
right = check_sub_tree_Right(node->right, min);
if (left == right && left == 1)
return (1);
return (0);
}
}
/**
* binary_tree_is_bst - says if a tree is a bst or not
* the process here is first verify that the left node be smaller than the root
* then verify if the right node is bigger than th root.
* after that verify if the left subtree has nodes smaller than root
* and the right subtree has bigger nodes than root
* @tree: node that point to the tree to check
* Return: 1 if it is a BST or 0 if not
*/
int binary_tree_is_bst(const binary_tree_t *tree)
{
int var = 0, left = 2, right = 2;
if (tree == NULL)
return (0);
if (tree->left && tree->left->n > tree->n)
return (0);
if (tree->right && tree->right->n < tree->n)
return (0);
if (tree->left && tree->left->n < tree->n)
{
var = check_sub_tree_Left(tree->left, tree->n);
if (var == 0)
return (0);
left = binary_tree_is_bst(tree->left);
}
if (tree->right && tree->right->n > tree->n)
{
var = check_sub_tree_Right(tree->right, tree->n);
if (var == 0)
return (0);
right = binary_tree_is_bst(tree->right);
}
if (left != 2 || right != 2)
{
if (left == 0 || right == 0)
return (0);
}
return (1);
}