University stuff.
Vous ne pouvez pas sélectionner plus de 25 sujets Les noms de sujets doivent commencer par une lettre ou un nombre, peuvent contenir des tirets ('-') et peuvent comporter jusqu'à 35 caractères.

TreeStats.java 1.6KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566
  1. import java.util.ArrayList;
  2. import java.util.List;
  3. class TreeStats {
  4. public static void printStats(BinTree tree) {
  5. // Nodes for each depth
  6. System.out.println("Num nodes for each depth:");
  7. int[] depths = new int[height(tree.first) + 1];
  8. numForDepth(tree.first, depths);
  9. for (int i = 0; i < depths.length; ++i) {
  10. System.out.println("\tDepth "+i+": "+depths[i]);
  11. }
  12. // Height
  13. System.out.println("Tree height: "+height(tree.first));
  14. // Average depth
  15. System.out.printf("Average depth: %.2f\n",
  16. (totalDepth(tree.first) / (double)numNodes(tree.first)));
  17. // First and last word
  18. System.out.println("First word: "+tree.findSmallest());
  19. System.out.println("Last word: "+tree.findBiggest());
  20. }
  21. public static int height(BinTree.Node node) {
  22. if (node.left == null && node.right == null)
  23. return 0;
  24. else if (node.left != null && node.right == null)
  25. return height(node.left) + 1;
  26. else if (node.left == null && node.right != null)
  27. return height(node.right) + 1;
  28. else {
  29. int lh = height(node.left);
  30. int rh = height(node.right);
  31. return (lh > rh ? lh : rh) + 1;
  32. }
  33. }
  34. public static int numNodes(BinTree.Node node) {
  35. if (node == null)
  36. return 0;
  37. return 1 + numNodes(node.left) + numNodes(node.right);
  38. }
  39. public static int totalDepth(BinTree.Node node) {
  40. if (node == null)
  41. return 0;
  42. return node.depth() + totalDepth(node.left) + totalDepth(node.right);
  43. }
  44. public static void numForDepth(BinTree.Node node, int[] acc) {
  45. if (node == null)
  46. return;
  47. acc[node.depth()] = acc[node.depth()] + 1;
  48. numForDepth(node.left, acc);
  49. numForDepth(node.right, acc);
  50. }
  51. }