Written interview algorithm Classic--Two-fork Tree substructure (Java) __ Code

Source: Internet
Author: User

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; }
    }

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.