-
Notifications
You must be signed in to change notification settings - Fork 1
/
Binary Search Tree.cs
77 lines (63 loc) · 1.8 KB
/
Binary Search Tree.cs
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
using System;
namespace Algorithm {
class BinarySearchTree {
class Node {
public int data;
public Node left, right;
public Node(int item) {
data = item;
left = null;
right = null;
}
}
Node root;
BinarySearchTree() {
root = null;
}
Node search(Node root, int data) {
if(root == null) {
Console.Write("Not Found\n");
return null;
}
if(root.data == data) {
Console.Write("Found At: " + root + "\n");
return root;
}
if(root.data < data) {
return search(root.right, data);
} else {
return search(root.left, data);
}
}
void insert(int data) {
root = recInsert(root, data);
}
Node recInsert(Node root, int data) {
if(root == null) {
root = new Node(data);
return root;
}
if(data <= root.data) {
root.left = recInsert(root.left, data);
} else {
root.right = recInsert(root.right, data);
}
return root;
}
public static void Main(string[] args){
BinarySearchTree t = new BinarySearchTree();
t.insert(5);
t.insert(3);
t.insert(8);
t.insert(1);
t.insert(4);
t.insert(7);
t.insert(9);
t.insert(0);
t.insert(2);
t.insert(6);
t.insert(10);
t.search(t.root, 10);
}
}
}