[Offer] to prove safety substructure tree (JS achieve)

Subject description:

Two binary inputs A, B, B is judged not substructure A's. (Ps: we agreed empty tree is not a tree any substructure)

Ideas: if A, B the same as the root value, which value is determined further subtree;
otherwise, the left subtree of A, find the right subtree

/* function TreeNode(x) {
    this.val = x;
    this.left = null;
    this.right = null;
} */ 
function HasSubtree(pRoot1, pRoot2)
{
   if (pRoot1 == null || pRoot2 == null) {
       return false;
   }
   //如果根节点相同,进一步比较其左子树右子树;
   //否则分别判断其左子树或右子树中是否包含
    return Subtree(pRoot1, pRoot2) || HasSubtree(pRoot1.left, pRoot2) || HasSubtree(pRoot1.right, pRoot2);
}

function Subtree(root1, root2) {
//如果第二棵遍历结束,则说明是是其子树
    if (root2 == null) return true;
    //如果第二棵没有结束,第一棵已经遍历完,则不是它的子树
    if (root1 == null) return false;
    //如果两个节点值相同,进一步判断其左子树右子树
    if (root1.val == root2.val) {
        return Subtree(root1.left, root2.left) &&
            Subtree(root1.right, root2.right);
    } else {
        return false;   
    }
}
Published 95 original articles · won praise 91 · views 10000 +

Guess you like

Origin blog.csdn.net/qq_43466457/article/details/104534210