-
Notifications
You must be signed in to change notification settings - Fork 0
/
TreeDS.java
95 lines (80 loc) · 1.99 KB
/
TreeDS.java
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
94
95
package oops;
//---------------------------------------BINARY TREE IMPLEMENTATION--------------------------by_Abd
class BT{
// Creating Node Structure//
class Node
{
int data;
Node left,right;
Node(int val) // Constructor for class Node
{
data=val;
left=null;
right=null;
}
}
Node root;// reference variable to store ref of root node
BT(int val)// constructor for Class BT
{
root = new Node(val);
}
// Inserting at Right side of the node
void insertLeftNode(Node n, int val)
{
Node newNode= new Node(val);
n.left=newNode;
}
//Inserting left side of the Node
void insertRightNode(Node n, int val)
{
Node newNode =new Node(val);
n.right=newNode;
}
// In Order Traversing (LEFT->ROOT->RIGHT)
static void InOrdertraverse(Node r)
{
if(r !=null)
{
InOrdertraverse(r.left);
System.out.print(r.data+" ");
InOrdertraverse(r.right);
}
}
// PRE ORDER TRAVERSING (ROOT->LEFT->RIGHT)
static void preOrdertraverse(Node r)
{
if(r !=null)
{
System.out.print(r.data+" ");
preOrdertraverse(r.left);
preOrdertraverse(r.right);
}
}
//POST ORDER TRAVERSING (LEFT->RIGHT->ROOT)
static void postOrdertraverse(Node r)
{
if(r !=null)
{
postOrdertraverse(r.left);
postOrdertraverse(r.right);
System.out.print(r.data+" ");
}
}
}
public class TreeDS {
public static void main(String[] args) {
BT tree = new BT(15);// Creating Obj for class BT
tree.insertLeftNode(tree.root,10);
tree.insertRightNode(tree.root, 17);
tree.insertLeftNode(tree.root.left, 8);
tree.insertRightNode(tree.root.left,11);
tree.insertRightNode(tree.root.right, 18);
tree.insertLeftNode(tree.root.right,16);
System.out.println("PRE ORDER TRAVERSAL");
BT.preOrdertraverse(tree.root);
System.out.println("\nIN ORDER TRAVERSAL");
BT.InOrdertraverse(tree.root);
System.out.println("\nPOST ORDER TRAVERSAL");
BT.postOrdertraverse(tree.root);
}
}