解法一:建树+递归

两部分任务,首先是建立二叉搜索树,用递归的方法插入新结点,其次是判断两棵是否相同,通过递归地遍历来判断。

  1. import java.io.BufferedReader;
  2. import java.io.IOException;
  3. import java.io.InputStreamReader;
  4. class Node {
  5. int val;
  6. Node left;
  7. Node right;
  8. public Node() {
  9. }
  10. public Node(int val) {
  11. this.val = val;
  12. }
  13. }
  14. public class Main {
  15. public static void main(String[] args) throws IOException {
  16. // 读入数据
  17. BufferedReader reader = new BufferedReader(new InputStreamReader(System.in));
  18. String[] strs;
  19. while (true) {
  20. strs = reader.readLine().split(" ");
  21. if (strs[0].equals("0") && (strs.length == 1)) {
  22. return;
  23. }
  24. int n = Integer.parseInt(strs[0]);
  25. int len = Integer.parseInt(strs[1]);
  26. Node base = buildTree(reader, n);
  27. for (int i = 0; i < len; ++i) {
  28. Node root = buildTree(reader, n);
  29. if (judge(base, root)) {
  30. System.out.println("Yes");
  31. } else {
  32. System.out.println("No");
  33. }
  34. }
  35. }
  36. }
  37. /**
  38. * 建树
  39. *
  40. * @param reader 输入
  41. * @param n 结点数
  42. * @return 树的根结点
  43. * @throws IOException
  44. */
  45. private static Node buildTree(BufferedReader reader, int n) throws IOException {
  46. String[] strs = reader.readLine().split(" ");
  47. Node root = new Node(Integer.parseInt(strs[0]));
  48. int val;
  49. for (int i = 1; i < n; ++i) {
  50. val = Integer.parseInt(strs[i]);
  51. insert(root, val);
  52. }
  53. return root;
  54. }
  55. /**
  56. * 向二叉搜索树中插入结点
  57. *
  58. * @param root 根结点
  59. * @param val 待插入的值
  60. */
  61. private static void insert(Node root, int val) {
  62. if ((root.left == null) && (val < root.val)) {
  63. root.left = new Node(val);
  64. }
  65. if ((root.right == null) && (val > root.val)) {
  66. root.right = new Node(val);
  67. }
  68. if (val < root.val) {
  69. insert(root.left, val);
  70. }
  71. if (val > root.val) {
  72. insert(root.right, val);
  73. }
  74. }
  75. /**
  76. * 判断两棵数是否相同
  77. *
  78. * @param rootA 树A
  79. * @param rootB 树B
  80. * @return 相同返回true, 否则返回false
  81. */
  82. private static boolean judge(Node rootA, Node rootB) {
  83. if (rootA == null && rootB == null) {
  84. return true;
  85. }
  86. if (rootA == null || rootB == null) {
  87. return false;
  88. }
  89. if (rootA.val != rootB.val) {
  90. return false;
  91. } else {
  92. return judge(rootA.left, rootB.left) && judge(rootA.right, rootB.right);
  93. }
  94. }
  95. }