[Swipe the question bank] Sword refers to the 17th question of the Offer_ programming question (implemented by JavaScript), the substructure of the tree.

Title description

Enter two binary trees A and B to determine whether B is a substructure of A. (Ps: We agree that the empty tree is not a substructure of any tree)

Time limit: 1 second Space limit: 32768K Heat index: 541328

Knowledge points of this question:  Binary Tree

/* function TreeNode(x) {
    this.val = x;
    this.left = null;
    this.right = null;
} */

//这里判断是否是子树
function isHasSubtree(pRoot1, pRoot2){
    if(pRoot2 == null)return true; // 如果二叉树B已经遍历完,这说明是二叉树A的子树
    if(pRoot1 == null)return false; //如果二叉树A提前遍历完,这说明二叉树B不是二叉树A的子树
    if(pRoot1.val != pRoot2.val) return false; //只要期间出现结点不同就不符合
    return isHasSubtree(pRoot1.left, pRoot2.left) && isHasSubtree(pRoot1.right, pRoot2.right);  //这里遍历二叉树A和二叉树B所有的的结点
}

//在二叉树A中找到二叉树B的根结点
function HasSubtree(pRoot1, pRoot2)
{
    var is = false;  
    if(pRoot1 == null || pRoot2 == null) return false;   //题目要求,我们约定空树不是任意一个树的子结构,还可判断无寻找到相同节点,二叉树B的根结点。
    if(pRoot1.val == pRoot2.val) is = isHasSubtree(pRoot1, pRoot2); //调用判断子树函数
    if(!is) is = HasSubtree(pRoot1.left, pRoot2);  //向二叉树A左子树查找
    if(!is) is = HasSubtree(pRoot1.right, pRoot2);  //向二叉树A右子树查找
    return is;
}

 

Guess you like

Origin blog.csdn.net/weixin_42339197/article/details/100053399