-
Notifications
You must be signed in to change notification settings - Fork 53
Expand file tree
/
Copy pathDetermine weather a given Binary Tree is BST.java
More file actions
74 lines (60 loc) · 1.44 KB
/
Determine weather a given Binary Tree is BST.java
File metadata and controls
74 lines (60 loc) · 1.44 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
class Node
{
int data;
Node left = null, right = null;
Node(int data) {
this.data = data;
}
}
class Main
{
public static Node insert(Node root, int key)
{
if (root == null) {
return new Node(key);
}
if (key < root.data) {
root.left = insert(root.left, key);
}
else {
root.right = insert(root.right, key);
}
return root;
}
public static boolean isBST(Node node, int minKey, int maxKey)
{
if (node == null) {
return true;
}
if (node.data < minKey || node.data > maxKey) {
return false;
}
return isBST(node.left, minKey, node.data) &&
isBST(node.right, node.data, maxKey);
}
public static void isBST(Node root)
{
if (isBST(root, Integer.MIN_VALUE, Integer.MAX_VALUE)) {
System.out.println("The tree is a BST.");
}
else {
System.out.println("The tree is not a BST!");
}
}
private static void swap(Node root)
{
Node left = root.left;
root.left = root.right;
root.right = left;
}
public static void main(String[] args)
{
int[] keys = { 15, 10, 20, 8, 12, 16, 25 };
Node root = null;
for (int key: keys) {
root = insert(root, key);
}
swap(root);
isBST(root);
}
}