输入两棵二叉树A和B,判断B是不是A的子结构。(约定空树不是任意一个树的子结构)
class Solution {
public boolean isSubStructure(TreeNode A, TreeNode B) {
boolean result= false;
if (A != null && B!= null) {
if (A.val == B.val) result = hasSubTree(A, B);
if (!result) result = isSubStructure(A.left, B);
if (!result) result = isSubStructure(A.right, B);
}
return result;
}
public boolean hasSubTree(TreeNode a, TreeNode b) {
// b 为空说明子树已经全部遍历完了
if (b == null) {
return true;
} else if (a == null) {
return false;
}
if (a.val != b.val) return false;
return hasSubTree(a.left, b.left) && hasSubTree(a.right, b.right);
}
}
网友评论