Created
December 3, 2012 10:44
-
-
Save bguzryanto/4194152 to your computer and use it in GitHub Desktop.
Tugas BST With Java
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
/** | |
* | |
* @author bagusrianto | |
*/ | |
import java.io.BufferedReader; | |
import java.io.IOException; | |
import java.io.InputStreamReader; | |
class NodeTree{ | |
int item; | |
NodeTree kiri; | |
NodeTree kanan; | |
NodeTree(int x) { | |
item = x; | |
} | |
} | |
/** | |
* | |
* @author Bagusrianto | |
*/ | |
public class TugasBST { | |
private static int hitung; | |
private static NodeTree root; | |
private static String alamat; | |
private static void main(String[] args) throws IOException { | |
int n; | |
String[] ans_string; | |
String s1; | |
alamat = ""; | |
BufferedReader in = new BufferedReader(new InputStreamReader(System.in)); | |
n = Integer.parseInt(in.readLine()); | |
s1 = in.readLine(); | |
ans_string = s1.split(" "); | |
for (int i = 0; i < n; ++i) { | |
sisipPohon(Integer.parseInt(ans_string[i])); | |
} | |
n = Integer.parseInt(in.readLine()); | |
s1 = in.readLine(); | |
ans_string = s1.split(" "); | |
for (int i = 0; i < n; ++i) { | |
pohonBerisi(root, Integer.parseInt(ans_string[i])); | |
} | |
} | |
private static boolean pohonBerisi(NodeTree simpul, int item) { | |
if (simpul == null) { | |
alamat = ""; | |
return false; | |
} else if (item == simpul.item) { | |
if (alamat.isEmpty()) { | |
System.out.println("O"); | |
} else { | |
System.out.println(alamat + "O"); | |
} | |
alamat = "kiri " + alamat; | |
return pohonBerisi(simpul.kiri, item); | |
} else if (item < simpul.item) { | |
alamat = "kiri " + alamat; | |
return pohonBerisi(simpul.kiri, item); | |
} else { | |
alamat = "kanan " + alamat; | |
return pohonBerisi(simpul.kanan, item); | |
} | |
} | |
private static void sisipPohon(int v) { | |
if (root == null) { | |
root = new NodeTree(v); | |
return; | |
} | |
NodeTree pointer; | |
pointer = root; | |
while (true) { | |
if (v <= pointer.item) { | |
if (pointer.kiri == null) { | |
pointer.kiri = new NodeTree(v); | |
return; | |
} else { | |
pointer = pointer.kiri; | |
} | |
} else { | |
if (pointer.kanan == null) { | |
pointer.kanan = new NodeTree(v); | |
return; | |
} else { | |
pointer = pointer.kanan; | |
} | |
} | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment