fork download
  1. class Node {
  2. int data;
  3. Node left, right;
  4.  
  5. public Node(int item) {
  6. data = item;
  7. left = right = null;
  8. }
  9. }
  10.  
  11. class BinaryTree {
  12. Node root;
  13.  
  14. BinaryTree() {
  15. root = null;
  16. }
  17.  
  18. void insert(int data) {
  19. root = insertRec(root, data);
  20. }
  21.  
  22. Node insertRec(Node root, int data) {
  23. if (root == null) {
  24. root = new Node(data);
  25. return root;
  26. }
  27.  
  28. if (data < root.data)
  29. root.left = insertRec(root.left, data);
  30. else if (data > root.data)
  31. root.right = insertRec(root.right, data);
  32.  
  33. return root;
  34. }
  35.  
  36. void preOrder(Node node) {
  37. if (node != null) {
  38. System.out.print(node.data + " ");
  39. preOrder(node.left);
  40. preOrder(node.right);
  41. }
  42. }
  43.  
  44. // Método para imprimir a árvore binária de forma gráfica
  45. void printTree(Node root, int nivel) {
  46. if (root != null) {
  47. printTree(root.right, nivel + 1);
  48. for (int i = 0; i < nivel; i++)
  49. System.out.print(" ");
  50. System.out.println(root.data);
  51. printTree(root.left, nivel + 1);
  52. }
  53. }
  54.  
  55. public static void main(String[] args) {
  56. BinaryTree tree = new BinaryTree();
  57. int[] values = {11, 6, 8, 19, 4, 10, 5, 17, 43, 49, 31};
  58.  
  59. for (int value : values) {
  60. tree.insert(value);
  61. }
  62.  
  63. System.out.println("Árvore Binária de Busca em pré-ordem:");
  64. tree.preOrder(tree.root);
  65.  
  66. System.out.println("\nÁrvore Binária de Busca:");
  67. tree.printTree(tree.root, 0);
  68. }
  69. }
  70.  
Success #stdin #stdout 0.1s 55692KB
stdin
Standard input is empty
stdout
Árvore Binária de Busca em pré-ordem:
11 6 4 5 8 10 19 17 43 31 49 
Árvore Binária de Busca:
         49
      43
         31
   19
      17
11
         10
      8
   6
         5
      4