题目说明B树如果为空树则不是A树的子结构
/**
* Definition for a binary tree node.
* public class TreeNode {
* int val;
* TreeNode left;
* TreeNode right;
* TreeNode(int x) { val = x; }
* }
*/
class Solution {
public boolean isSubStructure(TreeNode A, TreeNode B) {
if(B==null) return false;
return search(A,B);
}
public boolean search(TreeNode A, TreeNode B){
if(A==null) return false;
//比较该节点的值是否和B根节点相同,如果相同再判断是子树不是相同结构
if(A.val==B.val&&compare(A,B)){
return true;
}
//遍历左子树,遍历右子树
return search(A.left,B)||search(A.right,B);
}
public boolean compare(TreeNode A, TreeNode B){
if(B==null){
return true;
}
if(A==null){
return false;
}
//判断当前节点相不相等,左右子树相不相等
return A.val==B.val&&compare(A.left,B.left)&&compare(A.right,B.right);
}
}
优化之后代码如下:
class Solution {
public boolean isSubStructure(TreeNode A, TreeNode B) {
if(A == null || B == null) return false;
return compare(A, B) || isSubStructure(A.left, B) || isSubStructure(A.right, B);
}
public boolean compare(TreeNode A, TreeNode B){
if(B == null) return true;
if(A == null) return false;
return A.val == B.val && compare(A.left, B.left) && compare(A.right, B.right);
}
}