import java.io.BufferedReader; import java.io.InputStreamReader; import java.util.*; class TreeNode{ TreeNode left; TreeNode right; int val; public TreeNode(int val) { this.val = val; left = null; right = null; } } public class Main { public static Scanner sc = new Scanner(System.in); public static BufferedReader reader = new BufferedReader(new InputStreamReader(System.in)); public static long mod = (long) Math.pow(2, 29); public static void main(String[] args) throws Exception { String line; String[] strArr; line = reader.readLine(); strArr = line.split(" "); int n = Integer.valueOf(strArr[0]); int rootVal = Integer.valueOf(strArr[1]); Map<Integer, TreeNode> mp = new HashMap<>(n); for (int i = 0; i < n; i++) { line = reader.readLine(); strArr = line.split(" "); int val = Integer.valueOf(strArr[0]); int leftVal = Integer.valueOf(strArr[1]); int rightVal = Integer.valueOf(strArr[2]); if (!mp.containsKey(val)) { mp.put(val, new TreeNode(val)); } if (leftVal != 0) { if (!mp.containsKey(leftVal)) { mp.put(leftVal, new TreeNode(leftVal)); } mp.get(val).left = mp.get(leftVal); } if (rightVal != 0) { if (!mp.containsKey(rightVal)) { mp.put(rightVal, new TreeNode(rightVal)); } mp.get(val).right = mp.get(rightVal); } } TreeNode root = mp.get(rootVal); mp.clear(); line = reader.readLine(); strArr = line.split(" "); n = Integer.valueOf(strArr[0]); rootVal = Integer.valueOf(strArr[1]); for (int i = 0; i < n; i++) { line = reader.readLine(); strArr = line.split(" "); int val = Integer.valueOf(strArr[0]); int leftVal = Integer.valueOf(strArr[1]); int rightVal = Integer.valueOf(strArr[2]); if (!mp.containsKey(val)) { mp.put(val, new TreeNode(val)); } if (leftVal != 0) { if (!mp.containsKey(leftVal)) { mp.put(leftVal, new TreeNode(leftVal)); } mp.get(val).left = mp.get(leftVal); } if (rightVal != 0) { if (!mp.containsKey(rightVal)) { mp.put(rightVal, new TreeNode(rightVal)); } mp.get(val).right = mp.get(rightVal); } } TreeNode subRoot = mp.get(rootVal); boolean b = isInclude(root, subRoot); System.out.println(b ? "true": "false"); } static boolean isInclude(TreeNode root, TreeNode subRoot){ if(root == null){ return false; } return contains(root, subRoot) || isInclude(root.left, subRoot) || isInclude(root.right, subRoot); } // 必须确保树一样的 static boolean contains(TreeNode root1, TreeNode root2){ if(root1 == null && root2 != null){ return false; } if(root1 != null && root2 == null){ return false; } if(root1 == null && root2 == null){ return true; } if(root1.val != root2.val){ return false; } return contains(root1.left, root2.left) && contains(root1.right, root2.right); } } /* 9 1 1 2 3 2 4 5 4 0 8 8 0 0 5 9 0 9 0 0 3 6 7 6 0 0 7 0 0 5 2 2 4 5 4 0 8 8 0 0 5 9 0 9 0 0 true 9 1 1 2 3 2 4 5 4 0 8 8 0 0 5 9 0 9 0 0 3 6 7 6 0 0 7 0 0 4 2 2 4 5 4 0 8 8 0 0 5 0 0 false */
如下true
:
1 / \ 2 3 / \ / \ 4 5 6 7 \ / 8 9 2 / \ 4 5 \ / 8 9
如下false
:
1 / \ 2 3 / \ / \ 4 5 6 7 \ / 8 9 2 / \ 4 5 \ 8