Title Description:
Enter two binary trees, a, B, to determine whether a is a sub-structure of a. (PS: We agree that an empty tree is not a sub-structure of any tree) thought:
This is actually an application of binary tree traversal algorithm, in order to find out whether there is a lesson subtree in the original binary tree, it is only to determine whether each node is in the binary tree. Therefore, it is necessary to judge the head node first, only the head node meets the requirements to continue to compare its sub-tree is consistent, the same as in turn from the beginning of the node to compare until its left and right sub-tree comparison, if all conform to the B is a sub-structure. Code implementation:
/** 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) {Boolean hassubtree
= false; if (root1! = NULL && ROOT2! = null) {if (Root1.val = = root2.val) {Hassubtree = Nodesvale
Qual (ROOT1,ROOT2);
} if (!hassubtree) {hassubtree = Hassubtree (Root1.left,root2);
} if (!hassubtree) {hassubtree = Hassubtree (Root1.right,root2);
}} return hassubtree;
} Private Boolean nodesvalequal (TreeNode root1,treenode root2) {if (Root2 = = null) return true;
if (ROOT1 = = null) return false;
if (root1.val! = Root2.val) return false; Return nodesvalequal (Root1.left, Root2.left) && nodesvalequal (Root1.right, root2.right);
}
}