File size: 1,278 Bytes
c574d3a |
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 |
class Ins{
static Node root;
static class Node{
int data;
Node left;
Node right;
// constructor
Node(int d){
data = d;
left = null;
right = null;
}
}
static void Insertion(int key){
Node n = root;
Node r = null;
Node p = new Node(key);
if(root==null){
root = p;
return;
}
else{
while(n!=null){
r = n;
if(key<n.data){
n = n.left;
}
else if(key>n.data){
n = n.right;
}
else{
return;
}
}
if(p.data<r.data){
r.left = p;
}
else{
r.right = p;
}
}
}
static Node Rinsert(Node n,int key){
Node t = null;
if(n==null){
t = new Node(key);
return t;
}
if(key<n.data){
n.left = Rinsert(n.left,key);
}
else if(key>n.data){
n.right = Rinsert(n.right,key);
}
return n;
}
static void pre(Node n){
if(n!=null){
System.out.print(n.data+" ");
pre(n.left);
pre(n.right);
}
}
public static void main(String[] args){
Ins l = new Ins();
root = Rinsert(root, 42);
Rinsert(root, 3);
Rinsert(root, 4);
Rinsert(root, 8);
pre(root);
}
}
|