The substructure of a tree-the offer of a sword

Source: Internet
Author: User

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

    1. 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
    2. 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.
    3. 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

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.