Substructure "prove safety offer" 18 interview questions Java version tree

(Two binary inputs A and B, B is judged not substructure A of the lower supplement, according to the code book of view, the definition of the sub-structure does not include the null leaf nodes, that is to say as long as the presence of B of a digital a configuration is present in the line, then if B is null tree, it does not belong to the sub-structure a)

The book Method: The method of the book is very clear, is divided into two steps, first find root.val B A tree in the tree, then the point is determined by the structure down entirely contains the B-tree until the tree been traversed A .

    public boolean isChild(TreeNode aRoot, TreeNode bRoot){
        //A树没有遍历完而且B树不为空
        if(aRoot != null && bRoot != null){
            //在当前节点检查结构,或者去遍历当前节点的左节点或右节点。
            return isQualified(aRoot, bRoot) 
                    || isChild(aRoot.left, bRoot) 
                    || isChild(aRoot.right, bRoot);
        }
        //A树遍历完了或者B树是个null
        return false;
    }
    
    private boolean isQualified(TreeNode aRoot, TreeNode bRoot){
        //检查到了B的末尾
        if(bRoot == null)return true;
        
        //如果在检查完B之前A到了底
        if(aRoot == null)return false;
        
        //都不是null且val相等,继续检查
        if(aRoot.val == bRoot.val){
            return isQualified(aRoot.left, bRoot.left) 
                    && isQualified(aRoot.right, bRoot.right);
        }
        
        //都不是null但是val不等
        return false;
        
    }

My method: Start check whether B is empty, empty, then return false (define). aRoot and bRoot are two root nodes, and may switch between their root and child nodes. At the beginning, and if aRoot.val bRoot.val equal, then continues to compare the respective sub-nodes; if not equal the mobile aRoot and bRoot and compared.

    public boolean isChildTree(TreeNode aRoot, TreeNode bRoot){
        //定义,如果B树为空,返回false
        if(bRoot == null){
            return false;
        }
        return isChild2(aRoot, bRoot);
    }
    
    private boolean isChild2(TreeNode aRoot, TreeNode bRoot){
        //如果检查到了B的末尾
        if(bRoot == null)return true;
        
        //A到了末尾但是B没有
        if(aRoot == null)return false;
        
        //如果当前节点相同,进行进一步对比;
        //对比的结果可能是false,此时继续向下检查aRoot.left与bRoot、aRoot.right与bRoot
        if(aRoot.val == bRoot.val){
            return (isChild2(aRoot.left, bRoot.left) && isChild2(aRoot.right, bRoot.right))
                    || isChild2(aRoot.left, bRoot)
                    || isChild2(aRoot.right, bRoot);
        }else{//如果当前节点不同,继续向下检查aRoot.left与bRoot、aRoot.right与bRoot
            return isChild2(aRoot.left, bRoot)
                    || isChild2(aRoot.right, bRoot);
        }
    }

Guess you like

Origin www.cnblogs.com/czjk/p/11611905.html