1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53
| class Solution { public boolean isSubStructure(TreeNode A, TreeNode B) { if (A != null && B == null){ return false; } return dfs(A, B); }
public boolean dfs(TreeNode root, TreeNode B){ if (root == null){ return false; }
if (root.val == B.val){ if (compare(root, B)){ return true; } }
if (root.left != null){ if (dfs(root.left, B)){ return true; } }
if (root.right != null){ if (dfs(root.right, B)){ return true; } }
return false; }
public boolean compare(TreeNode A, TreeNode B){ if (A == null && B == null){ return true; } if (A != null && B == null) { return true; } if (A == null && B != null) { return false; }
if (A.val != B.val){ return false; }
return compare(A.left, B.left) && compare(A.right, B.right); } }
|