数的子结构

题目描述

输入两棵二叉树A,B,判断B是不是A的子结构。(ps:我们约定空树不是任意一个树的子结构)
 1 /**
 2 public class TreeNode {
 3     int val = 0;
 4     TreeNode left = null;
 5     TreeNode right = null;
 6 
 7     public TreeNode(int val) {
 8         this.val = val;
 9 
10     }
11 
12 }
13 */
14 public class Solution {
15     public boolean check(TreeNode root1, TreeNode root2) {
16         if (root2 == null) return true;
17         if (root1 == null && root2 != null) return false;
18         if (root1.val != root2.val) return false;
19         return check(root1.left, root2.left) && check(root1.right, root2.right);
20     }
21     public boolean HasSubtree(TreeNode root1,TreeNode root2) {
22         boolean flag = false;
23         if (root2 == null) return false;
24         if (root1 == null) return false;
25         if (root1.val == root2.val && check(root1, root2)) {
26             return true;
27         } else {
28             flag = HasSubtree(root1.left, root2) || HasSubtree(root1.right, root2);
29             return flag;
30         }
31     }
32 }
原文地址:https://www.cnblogs.com/hyxsolitude/p/12335862.html