-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathtrees10.c
86 lines (77 loc) · 1.89 KB
/
trees10.c
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
// Check if a given Binary Tree is BST
// Slow solution (Time Complexity O(n^2))
#include <stdio.h>
#include <stdlib.h>
#include <stdbool.h>
#include "print.h"
BstNode *Insert(BstNode *root, int data);
BstNode* GetNewNode(int data);
bool IsSubtreeLesser(BstNode *root, int value)
{
if (root == NULL) return true;
if (root -> data <= value
&& IsSubtreeLesser(root -> left, value)
&& IsSubtreeLesser(root -> right, value))
return true;
else
return false;
}
bool IsSubtreeGreater(BstNode *root, int value)
{
if (root == NULL) return true;
if (root -> data > value
&& IsSubtreeGreater(root -> left, value)
&& IsSubtreeGreater(root -> right, value))
return true;
else
return false;
}
bool IsBinarySearchTree(BstNode *root)
{
if (root == NULL) return true;
if (IsSubtreeLesser(root -> left, root -> data)
&& IsSubtreeGreater(root->right, root->data)
&& IsBinarySearchTree(root->left)
&& IsBinarySearchTree(root->right))
return true;
else
return false;
}
int main(void)
{
BstNode *root = NULL;
root = Insert(root,15);
root = Insert(root,10);
root = Insert(root,20);
root = Insert(root,20);
root = Insert(root,20);
root = Insert(root,12);
root = Insert(root,55);
printBST(root,0);
printf("%s\n", IsBinarySearchTree(root) ? "true" : "false");
}
BstNode *Insert(BstNode *root, int data)
{
if (root == NULL)
{
root = GetNewNode(data);
return root;
}
else if(data <= root -> data)
{
root -> left = Insert(root -> left, data);
}
else
{
root -> right = Insert(root -> right, data);
}
return root;
}
BstNode *GetNewNode(int data)
{
BstNode *newNode = malloc(sizeof(BstNode));
newNode -> data = data;
newNode -> left = NULL;
newNode -> right = NULL;
return newNode;
}