Definition: The parent tree contains all the nodes of the subtree, note that the empty tree is not a subtree of any number.
Parent Tree: A
Sub-tree: B
Solution: With the recursive implementation, starting from the root node of a tree, to determine whether all its nodes are the same as the tree B, such as different, recursive call function, continue to determine the tree a current node of the left subtree of all nodes or the right subtree all nodes are the same as tree B all nodes, until traverse to the parent tree a leaf node, If it is not exactly the same, Tree B is not a subtree of tree a, and if all its nodes are in tree A, until the leaf node of tree B is traversed, tree B is a subtree of tree a.
The code is as follows:
/** public
class TreeNode {
int val = 0;
TreeNode left = null;
TreeNode right = null;
Public TreeNode (int val) {
this.val = val;
}
}
*
/public class Solution {public
Boolean hassubtree (TreeNode root1,treenode root2) {
if (root1==null| | Root2==null) {
return false;
}
Return Issubtree (root1,root2) | | Hassubtree (root1.left,root2) | | Hassubtree (Root1.right,root2);
}
public boolean issubtree (TreeNode root1,treenode root2) {
if (root2==null) {
return true;
}
if (root1==null) {
return false;
}
if (root1.val==root2.val) {
return Issubtree (root1.left,root2.left) &&issubtree (Root1.right, root2.right);
}
return false;
}
}