Estrutura de dados
Questão 1
class TreeNode{
TreeNode left; int data; TreeNode right;
public TreeNode(int d) { data = d; left = right = null; }
public synchronized void insert(int d) { if (left == null) left = new TreeNode(d); else { if (right == null) right = new TreeNode(d); else { if((left.left != null && left.right != null) && (right.left == null || right.right == null)) right.insert(d); else left.insert(d); } } }
}
class Tree{ private TreeNode root;
public Tree() { root = null; }
public synchronized void insertNode (int d){ if (root == null) root = new TreeNode(d); else root.insert(d); }
public synchronized void preorderTraversal() { preorderHelper(root); }
private void preorderHelper(TreeNode node) { if (node == null) return;
System.out.print(node.data + " "); preorderHelper(node.left); preorderHelper(node.right); }
}
import java.util.Scanner; public class TreeBinary{ public static void main(String args[]) { Tree tree = new Tree(); int intVal; String cont = " "; Scanner sc = new Scanner(System.in); System.out.println("Digite um valor a inserir ou '0' para encerrar: "); intVal = sc.nextInt(); cont = Integer.toString(intVal); if(intVal == 0){ System.out.println("Árvore está vazia."); return; }else{ while(intVal != 0){ System.out.print(cont+" "); tree.insertNode(intVal); intVal = sc.nextInt(); cont = cont + " " + intVal; } }
System.out.println("\nPercorrendo a Árvore em ordem"); tree.preorderTraversal(); System.out.println();
}
}