Topic Description
Enter two binary tree a,b to determine whether B is a substructure (the empty tree is not a substructure of any tree). In the figure below: The two-fork tree on the right is the substructure of the left binary tree
Solution:
First to traverse A tree, if the current node is the same as the root node of the B tree, it is judged that B is not a subtree, and that B is a subtree of a is also recursive: the comparison of B's Zuozi is the substructure of a left subtree, and whether the right subtree of B is the substructure of the right subtree of a. So it takes two functions to do it, a function for the first order traversal, one to determine whether it is a subtree.
/* Class treenode{int val;
TreeNode Left=null;
TreeNode Right=null;
Public TreeNode (int val) {this.val = val; } */public static Boolean Hassubtree (TreeNode root1,treenode root2) {if (root1==null) | |
(Root2==null))
return false;
Returns False when a B is null, has traversed to the leaf node, and does not have the same node.
Boolean result=false; If the node in a is the same as the head node of B, then Judge B is not a subtree of a.
If not, look at the left subtree of a, or look at the right subtree of a.
if (root1.val==root2.val) {result=issubtree (ROOT1,ROOT2);
} if (!result) {result=hassubtree (root1.left, Root2);
} if (!result) {result=hassubtree (root1.right, Root2);
return result;
}//Judge B is not a sub structure.
public static 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);
else {return false; }
}