解法一:建树+递归
两部分任务,首先是建立二叉搜索树,用递归的方法插入新结点,其次是判断两棵是否相同,通过递归地遍历来判断。
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
class Node {
int val;
Node left;
Node right;
public Node() {
}
public Node(int val) {
this.val = val;
}
}
public class Main {
public static void main(String[] args) throws IOException {
// 读入数据
BufferedReader reader = new BufferedReader(new InputStreamReader(System.in));
String[] strs;
while (true) {
strs = reader.readLine().split(" ");
if (strs[0].equals("0") && (strs.length == 1)) {
return;
}
int n = Integer.parseInt(strs[0]);
int len = Integer.parseInt(strs[1]);
Node base = buildTree(reader, n);
for (int i = 0; i < len; ++i) {
Node root = buildTree(reader, n);
if (judge(base, root)) {
System.out.println("Yes");
} else {
System.out.println("No");
}
}
}
}
/**
* 建树
*
* @param reader 输入
* @param n 结点数
* @return 树的根结点
* @throws IOException
*/
private static Node buildTree(BufferedReader reader, int n) throws IOException {
String[] strs = reader.readLine().split(" ");
Node root = new Node(Integer.parseInt(strs[0]));
int val;
for (int i = 1; i < n; ++i) {
val = Integer.parseInt(strs[i]);
insert(root, val);
}
return root;
}
/**
* 向二叉搜索树中插入结点
*
* @param root 根结点
* @param val 待插入的值
*/
private static void insert(Node root, int val) {
if ((root.left == null) && (val < root.val)) {
root.left = new Node(val);
}
if ((root.right == null) && (val > root.val)) {
root.right = new Node(val);
}
if (val < root.val) {
insert(root.left, val);
}
if (val > root.val) {
insert(root.right, val);
}
}
/**
* 判断两棵数是否相同
*
* @param rootA 树A
* @param rootB 树B
* @return 相同返回true, 否则返回false
*/
private static boolean judge(Node rootA, Node rootB) {
if (rootA == null && rootB == null) {
return true;
}
if (rootA == null || rootB == null) {
return false;
}
if (rootA.val != rootB.val) {
return false;
} else {
return judge(rootA.left, rootB.left) && judge(rootA.right, rootB.right);
}
}
}