The sword refers to offer--18. The substructure of the tree

Question: Input two binary trees A and B, and determine whether B is a substructure of A.
public class wr18hasSubTree {
// Step 1: Find a node in tree A that has the same value as the root node
	public boolean HasSubtree(TreeNode root1,TreeNode root2) {
		boolean result=false;
// Compare when both tree1 and tree2 are not 0, otherwise return false directly
		if(root2!=null && root1!=null){
// If the point corresponding to the root node of tree2 is found, use this root node as the starting point to determine whether tree2 is included
			if(root1.val==root2.val){
				result=doesTree1HaveTree2(root1,root2);
			}
// If it is not found, the left child of root is used as the starting point to determine whether it contains tree2
			if(!result){
				result=HasSubtree(root1.left,root2);
			}
// If it is not found, the right son of root is used as the starting point
			if(!result){
				result=HasSubtree(root1.right,root2);
			}
		}
		return result;
    }
// The second step is to determine whether the subtree with R as the root node in tree A has the same structure as tree B
// Ideas: If the value of node R is different from the root node of tree B, then the subtree with R as the root node and tree B must not have the same node
// If their values ​​are the same, recursively determine whether the values ​​of their respective left and right nodes are the same
// The termination condition of the recursion is that we reach the leaf node of tree A or tree B
	public static boolean doesTree1HaveTree2(TreeNode node1,TreeNode node2){
		if(node2==null){
			return true;
		}
		if(node1==null){
			return false;
		}

		if(node1.val!=node2.val){
			return false;
		}

		return doesTree1HaveTree2(node1.left,node2.left)&&doesTree1HaveTree2(node1.right,node2.right);
	}
}

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=325650967&siteId=291194637