[Deslizar el banco de preguntas] Sword se refiere a la pregunta 17 de la pregunta de programación Offer_ (implementada por JavaScript), la subestructura del árbol.

Descripción del Título

Ingrese dos árboles binarios A y B para determinar si B es una subestructura de A. (Ps: estamos de acuerdo en que el árbol vacío no es una subestructura de ningún árbol)

Límite de tiempo: 1 segundo Límite de espacio: 32768K Índice de calor: 541328

Puntos de conocimiento de esta pregunta:  árbol binario

/* 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;
}

 

Supongo que te gusta

Origin blog.csdn.net/weixin_42339197/article/details/100053399
Recomendado
Clasificación