Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- import java.util.LinkedList;
- import java.util.List;
- import java.util.Scanner;
- class Node<T> {
- T data;
- LinkedList<Node> childs;
- public Node(T data) {
- this.data = data;
- this.childs = new LinkedList<Node>();
- }
- public T getData(){
- return this.data;
- }
- }
- public class Tree<T> {
- Node root;
- public Tree(Node node) {
- root = node;
- }
- public Tree(T data) {
- root = new Node(data);
- }
- public boolean isEmpty() {
- return root == null;
- }
- public void add(T dataParent, T data) {
- Node node = getNode(root, dataParent);
- if (node != null)
- node.childs.add(new Node(data));
- else
- System.out.println("Node Parent tidak ditemukan");
- }
- public Node getNode(Node node, T data) {
- if (node.data == data) return node;
- for(Object currNode : node.childs) {
- Node returnNode = getNode((Node) currNode, data);
- if (returnNode != null) return returnNode;
- }
- return null;
- }
- public void printLeaves(Node current){
- //LENGKAPI
- if (!current.childs.isEmpty()) {
- current.childs.forEach((child) -> {
- printLeaves((Node) child);
- });
- } else {
- System.out.print(current.data + " ");
- }
- }
- public void access() {
- System.out.print(root.data);
- access(root, " ");
- }
- private void access(Node node, String space) {
- System.out.println("");
- for(Object currNode : node.childs) {
- System.out.print(space + "->" + ((Node) currNode).getData());
- access((Node) currNode, space + " ");
- }
- return;
- }
- public static void main(String[] args) {
- Scanner in = new Scanner(System.in);
- int n = in.nextInt();
- int rt = in.nextInt();
- Tree pohon = new Tree(new Node(rt));
- for (int i = 0; i < n-1; i++) {
- int p = in.nextInt();
- int nd = in.nextInt();
- pohon.add(p, nd);
- }
- pohon.access();
- pohon.printLeaves(pohon.root);
- System.out.println("");
- }
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement