给定两颗二叉树A和B,如何判断B是不是A的子结构,本文将分享一个方案用来解决此问题,欢迎各位感兴趣的开发者阅读本文。
在我的数据结构与算法实现系列文章——实现二叉搜索树中,我们知道了二叉树最多只能有两个子节点:左子节点、右子节点。那么,在本题中要判断是否包含,可以分为两步来实现:

image-20220630222011000
通过上个章节的分析,我们已经得出了具体的思路,接下来,我们就将思路转换为代码,如下所示:
export function TreeSubstructure(
treeA: BinaryTreeNode | null | undefined,
treeB: BinaryTreeNode | null | undefined
): boolean {
let result = false;
if (treeA != null && treeB != null) {
// 两个节点相同
if (treeA.key === treeB.key) {
// 判断树A中是否包含树B
result = treeAHaveTreeB(treeA, treeB);
}
// 继续寻找左子树与右子树
if (!result) {
result = TreeSubstructure(treeA?.left, treeB);
}
if (!result) {
result = TreeSubstructure(treeA?.right, treeB);
}
}
return result;
}
function treeAHaveTreeB(
treeA: BinaryTreeNode | null | undefined,
treeB: BinaryTreeNode | null | undefined
): boolean {
// 递归到了树B的叶节点,代表该节点存在于树A中
if (treeB == null) {
return true;
}
// 递归到树A的叶节点,代表该节点不存在于树A中
if (treeA == null) {
return false;
}
if (treeA.key !== treeB.key) {
return false;
}
// 左子树与右子树都相同
return (
treeAHaveTreeB(treeA?.left, treeB?.left) &&
treeAHaveTreeB(treeA?.right, treeB?.right)
);
}
注意:上述代码中用到了递归,如果你对其不了解,可以移步我的另一篇文章:递归的理解与实现 代码中还用到了一个自定义类型BinaryTreeNode,具体的类型定义请移步示例代码章节。
接下来,我们用思路分析章节中所举的例子来测试下上述函数能否正确执行。
const treeA: BinaryTreeNode = {
key: 8,
left: {
key: 8,
left: { key: 9 },
right: { key: 2, left: { key: 4 }, right: { key: 7 } }
},
right: { key: 7 }
};
const treeB: BinaryTreeNode = {
key: 8,
left: {
key: 9
},
right: {
key: 2
}
};
const result = TreeSubstructure(treeA, treeB);
console.log("treeA中包含treeB", result);

image-20220630223617368
本文所用代码完整版请移步👇:
至此,文章就分享完毕了。
我是神奇的程序员,一位前端开发工程师。
如果你对我感兴趣,请移步我的个人网站,进一步了解。