The sub-structure of the tree topic description
Enter two binary trees, a, B, to determine whether a is a sub-structure of a.
Ideas
Two steps to achieve
- First judge the node in the Tree1 is not the same as the root node of the Tree2 is worth the node, recursive judgment, if there is, side to judge the second step, otherwise, return false
- From the node that has the same value, judge whether the sub-tree is equal to the left and right of the recursion, and note the condition of the null pointer.
- Note: When writing the code traversing the tree must be highly vigilant, in every place to access the address of the time to ask yourself if this address is not possible null, if it is how to handle. (To ensure that your code is complete and correct, use several test cases to test your program after writing the code)
Code
/**public classTreeNode {int val =0;TreeNode left = null;TreeNode right = null; PublicTreeNode (int val) {this.val = val;}} */public classSolution {Public BooleanHassubtree (TreeNode Root1,TreeNode Root2) {Booleanresult =Falseif (root1! = NULL && ROOT2! = null) {if (Root1.val = = Root2.val) {result =Doestree1hastree2 (ROOT1, Root2);}if (!Result) {result =Hassubtree (Root1.left, Root2);}if (!Result) {result = hassubtree (Root1.right, Root2);}} return result;} public boolean doestree1hastree2 (treenode root1, treenode Root2) {if (Root2 = null) {return true;} if (ROOT1 = null) {return FALSE;} if (root1.val! = root2.val) {return FALSE;} return doestree1hastree2 (Root1.left, Root2.left) && Span class= "Hljs-type" >doestree1hastree2 (Root1.right, root2.right);}
Sub-structure of the tree-sword point offer