/** * Do not move A to traverse B first * @author Lucas * @date 2021/02/08 23:31 * @param A given tree * @param B substructure * @return boolean */ public static boolean isSubStructure(TreeNode A, TreeNode B) { // Recursive exit if (A == null || B == null) { return false; } // Recursively find the subtree rooted in A with the root node of B as the root return compare(A, B) || isSubStructure(A.left, B) || isSubStructure(A.right, B); } /** * A, B compare to determine whether B is a substructure of A * @author Lucas * @date 2021/02/08 23:32 * @param A given tree * @param B substructure * @return boolean */ public static boolean compare(TreeNode A, TreeNode B){ // When B is empty, it proves that the matching has been completed if (B == null){ return true; } if (A == null || A.val != B.val){ return false; } // Recursive AB to the left or right at the same time return compare(A.left, B.left) && compare(A.right, B.right); }
Sword refers to the substructure of the Offer-24 tree
Guess you like
Origin blog.csdn.net/a792396951/article/details/113767527
Recommended
Ranking