Prove safety offer: sub-tree (java)

Title: two binary inputs A and B, B is not determined substructure A's.

For example, two binary tree shown in the drawing, since the A part of the sub-tree structure and B is the same, so the sub-structure A is B.


To find whether there is a B tree and sub-tree structure as well as A, the idea is the first step: to find the same value of the root node in the tree A, which is in fact a preorder traversal of the tree, when the tree a and B are empty tree output corresponding definitions. If the value B and the head node tree A tree of a node is the same, it is called doesTree1HaveTree2, a second step to make determination. A second step is to decision tree R is a subtree rooted tree is not and B have the same structure, using a recursive method to consider: If the tree root node R and B is false if not identical, If so, the value thereof is determined recursively around the node is not the same. We arrived recursion tree termination condition A or B is a tree leaf node.

  public boolean hasSubTree(BinaryTreeNode root1,BinaryTreeNode root2){  
        if(root2 == null)  
            return true;  
        if(root1 == null)  
            return false;  
        boolean result = false;  
          
        if(root1 != null && root2 != null){  
            if(root1.value == root2.value)  
                result = doesTree1HaveTree2(root1,root2);  
            if(!result)  
                result = hasSubTree(root1.leftNode,root2);  
            if(!result)  
                result = hasSubTree(root1.rightNode ,root2);  
        }  
        return result;  
    }  
    public boolean doesTree1HaveTree2(BinaryTreeNode root1,BinaryTreeNode root2){  
        if(root2 == null)  
            return true;  
        if(root1 == null)  
            return false;  
        if(root1.value != root2.value)  
            return false;  
        return doesTree1HaveTree2(root1.leftNode,root2.leftNode) && doesTree1HaveTree2(root1.rightNode,root2.rightNode);  
    }  
Test Case:

Function Test (Tree A and B are ordinary binary tree, the tree is a B tree substructure A or not) of

Special test input (a binary or two courses of two root pointer to NULL, all nodes of the binary tree or subtree are not left right subtree)

Published 118 original articles · won praise 35 · views 120 000 +

Guess you like

Origin blog.csdn.net/abc7845129630/article/details/52724765