Skip to content

Commit 93fc34b

Browse files
committed
reverse traversal of bst
1 parent 5b55b8e commit 93fc34b

File tree

1 file changed

+98
-0
lines changed

1 file changed

+98
-0
lines changed

Assignments/reverseTT.java

Lines changed: 98 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,98 @@
1+
import java.util.*;
2+
public class reverseTT
3+
{
4+
Node root;
5+
class Node
6+
{
7+
int data;
8+
Node right,left;
9+
Node(int data)
10+
{
11+
this.data=data;
12+
right=left=null;
13+
}
14+
}
15+
void insert(int data)
16+
{
17+
root=insertRec(root,data);
18+
}
19+
Node insertRec(Node root,int data)
20+
{
21+
if(root==null)
22+
{
23+
root=new Node(data);
24+
return root;
25+
}
26+
if(data<root.data)
27+
{
28+
root.left=insertRec(root.left, data);
29+
}
30+
else if(data>root.data)
31+
{
32+
root.right=insertRec(root.right, data);
33+
}
34+
return root;
35+
}
36+
int height(Node root)
37+
{
38+
int c=0,c1=0;
39+
if(root==null)
40+
{
41+
return 0;
42+
}
43+
if(root!=null)
44+
{
45+
c=height(root.left);
46+
c++;
47+
c1=height(root.right);
48+
c1++;
49+
}
50+
if(c>c1)
51+
return c;
52+
else
53+
return c1;
54+
55+
}
56+
void print(Node root)
57+
{
58+
int height=height(root);
59+
for(int i=height;i>=1;i--)
60+
{
61+
revlevprint(root,i);
62+
}
63+
64+
}
65+
// reverse level printing of bst
66+
void revlevprint(Node root,int level)
67+
{
68+
if(root==null)
69+
return;
70+
if(level==1)
71+
System.out.print(root.data+" ");
72+
else
73+
revlevprint(root.left,level-1);
74+
revlevprint(root.right,level-1);
75+
76+
77+
}
78+
79+
public static void main(String args[])
80+
{
81+
reverseTT tree=new reverseTT();
82+
Scanner sc=new Scanner(System.in);
83+
System.out.println("Enter the number of nodes");
84+
int num = sc.nextInt();
85+
System.out.println("Enter nodes");
86+
/*Enter the data nodes in PreOrder or just enter root node first*/
87+
for(int i =0 ; i<num ; i++)
88+
{
89+
tree.insert(sc.nextInt());
90+
}
91+
tree.print(tree.root);
92+
// int h1=tree.height(tree.root);
93+
// System.out.println("Height of tree "+h1);
94+
95+
96+
}
97+
98+
}

0 commit comments

Comments
 (0)