The sub-structure of the offer--tree

Source: Internet
Author: User
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);       
    }
} 

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.