Subestructura del árbol (vs subárbol)

Tema: 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)

Nota: La subestructura es una parte del árbol, no necesariamente el subárbol.

/ * 
struct TreeNode { 
	int val; 
	struct TreeNode * left; 
	struct TreeNode * right; 
	TreeNode (int x): 
			val (x), left (NULL), right (NULL) { 
	} 
}; * / 
class Solution { 
public: 
    bool judge (TreeNode * pRoot1, TreeNode * pRoot2) { 
        if (pRoot1 == NULL && pRoot2 == NULL) devuelve verdadero; 
        if (pRoot1 == NULL) devuelve falso; 
        if (pRoot2 == NULL) devuelve verdadero; 
        if (pRoot1 -> val! = pRoot2 -> val) devuelve falso; 
        juez de retorno (pRoot1 -> izquierda, pRoot2 -> izquierda) && juez (pRoot1 -> derecha, pRoot2 -> derecha); 
    } 
    bool HasSubtree (TreeNode * pRoot1, TreeNode * pRoot2) 
    {
        if (pRoot1 == NULL) devuelve falso; 
        if (pRoot2 == NULL) devuelve falso; 
        if (pRoot1 -> val == pRoot2 -> val) { 
            if (judge (pRoot1, pRoot2)) devuelve verdadero; 
        } 
        return HasSubtree (pRoot1 -> left, pRoot2) || HasSubtree (pRoot1 -> derecha, pRoot2); 
    } 
};

Tema: Determine si B es un subárbol de A.

solución de clase { 
public: 
    bool judge (TreeNode * pRoot1, TreeNode * pRoot2) { 
        if (pRoot1 == NULL && pRoot2 == NULL) return true; 
        if (pRoot1 == NULL) devuelve falso; 
        if (pRoot2 == NULL) devuelve falso; 
        if (pRoot1 -> val! = pRoot2 -> val) devuelve falso; 
        juez de retorno (pRoot1 -> izquierda, pRoot2 -> izquierda) && juez (pRoot1 -> derecha, pRoot2 -> derecha); 
    } 
    bool HasSubtree (TreeNode * pRoot1, TreeNode * pRoot2) 
    { 
        if (pRoot1 == NULL) devuelve falso; 
        if (pRoot2 == NULL) devuelve falso; 
        if (pRoot1 -> val == pRoot2 -> val) { 
            if (judge (pRoot1, pRoot2)) devuelve verdadero;
        }
        devuelve HasSubtree (pRoot1 -> left, pRoot2) || HasSubtree (pRoot1 -> derecha, pRoot2); 
    } 
};

  

Supongo que te gusta

Origin www.cnblogs.com/tyty-Somnuspoppy/p/12713893.html
Recomendado
Clasificación