/** * Definition for a binary tree node. * public class TreeNode { * int val; * TreeNode left; * TreeNode right; * TreeNode(int x) { val = x; } * } */ classSolution{ publicbooleanisSubStructure(TreeNode A, TreeNode B){ if (A == null || B == null) { returnfalse; } //当前根,左右子树 //本质上,这里就是先序遍历A数,然后遍历比较B数 return recursive(A, B) || isSubStructure(A.left, B) || isSubStructure(A.right, B); }
//以当前节点判断,B是不是子树 publicbooleanrecursive(TreeNode A, TreeNode B){ if (B == null) { returntrue; } if (A==null||A.val!=B.val) returnfalse; return recursive(A.left, B.left) && recursive(A.right, B.right); }