题目描述
输入两棵二叉树A,B,判断B是不是A的子结构。(ps:我们约定空树不是任意一个树的子结构)
思路
使用递归,逐一比较左右子节点
Code
- JavaScript
/* function TreeNode(x) {
this.val = x;
this.left = null;
this.right = null;
} */
function HasSubtree(a, b)
{
// write code here
if (a == null || b == null) return false;
return isSubtree(a, b) || HasSubtree(a.left, b) || HasSubtree(a.right, b);
}
function isSubtree(a, b)
{
if (b == null) return true;
if (a == null) return false;
if (a.val === b.val) {
return isSubtree(a.left, b.left) && isSubtree(a.right, b.right)
}
return false;
}
网友评论