package JianZhioffer; /** * 输入两棵二叉树A和B,判断B是不是A的子结构。(约定空树不是任意一个树的子结构) B是A的子结构, 即 A中有出现和B相同的结构和节点值。 */ //不相等之后不能返回来判断子树,直接返回不是子结构,再进入左右子树 public class test26 { public static void main(String[] args) { TreeNode t=new TreeNode(4); t.left=new TreeNode(2); t.right=new TreeNode(3); t.left.left=new TreeNode(4); t.left.right=new TreeNode(5); t.right.left=new TreeNode(6); t.right.right=new TreeNode(7); t.left.left.left=new TreeNode(8); t.left.left.right=new TreeNode(9); TreeNode r=new TreeNode(4); r.left=new TreeNode(8); r.right=new TreeNode(9); System.out.println(isSubStructure(t, r)); } public static boolean isSubStructure(TreeNode A, TreeNode B) { if(A==null||B==null){ return false; } return helper(A, B)||isSubStructure(A.left,B)||isSubStructure(A.right, B); } public static boolean helper(TreeNode A, TreeNode B){ if(B==null){ return true; } if(A==null||A.val!=B.val){ return false; } return helper(A.left,B.left)&&helper(A.right,B.right); } }