{"id":1955,"date":"2024-03-13T18:00:00","date_gmt":"2024-03-13T18:00:00","guid":{"rendered":"https:\/\/favtutor.com\/articles\/?p=1955"},"modified":"2024-03-14T10:41:35","modified_gmt":"2024-03-14T10:41:35","slug":"subtree-of-another-tree","status":"publish","type":"post","link":"https:\/\/favtutor.com\/articles\/subtree-of-another-tree\/","title":{"rendered":"Check If Binary Tree is Subtree of Another Tree (with code)"},"content":{"rendered":"\n<p>Trees are an important data structure but are difficult to master. There are many questions asked in interviews based on the tree, but here we will solve the &#8216;Subtree of Another Tree&#8217; problem with solutions in C++, Java, and Python. <\/p>\n\n\n\n<h2 class=\"wp-block-heading\"><strong>Subtree of Another Tree problem<\/strong><\/h2>\n\n\n\n<p>In the Subtree of Another Tree problem, we are given the roots of two binary trees A and B. We have to find if there is any subtree of A having the same structure and values as subtree B.\u00a0<\/p>\n\n\n\n<p>Here are some examples which show which are subtree and which are not:<\/p>\n\n\n\n<figure class=\"wp-block-image\"><img decoding=\"async\" src=\"https:\/\/lh7-us.googleusercontent.com\/UocdTtmx_9vEYwnv4EJe9eE8N3De8BgpT5Ph3bu3G6Tr2XmwpNnWKp6F0AL5XlY9S-PtKCJCk1NcO0LeXbonSPm7vjf0vaNJjahkqzo1roxgjRVPOZs_i9ZOLdPv-vMyHIUOupokh6bXRoMWyc3rKyI\" alt=\"Example of Subtree of Another Tree problem\"\/><\/figure>\n\n\n\n<h2 class=\"wp-block-heading\"><strong>Recursive Approach<\/strong><\/h2>\n\n\n\n<p>To find whether the given subtree is a subtree of A or not. We have to recursively traverse tree A and check at each node whether this subtree is the same as subtree B. If it is return true otherwise traverse the left and right node. If there is no such tree you have to return false.<\/p>\n\n\n\n<p>Let\u2019s find out how to do it step-by-step:<\/p>\n\n\n\n<ol class=\"wp-block-list\">\n<li>You have to traverse each node of tree A.<\/li>\n\n\n\n<li>Check if any of the nodes of trees A and B are null and return false.<\/li>\n\n\n\n<li>If both the nodes are null return true.<\/li>\n\n\n\n<li>Now check if the value is the same for both nodes or not. If it is check if both the trees, tree B and subtree of A are the same if it is return true.<\/li>\n\n\n\n<li>If not check for left and right subtree.<\/li>\n\n\n\n<li>Repeat the same process<\/li>\n<\/ol>\n\n\n\n<p>Let\u2019s examine the code for the above process.<\/p>\n\n\n\n<h3 class=\"wp-block-heading\"><strong>C++ Code<\/strong><\/h3>\n\n\n\n<p>Here is the C++ program to check if a binary tree is a subtree of another tree:<\/p>\n\n\n\n<div class=\"wp-block-codemirror-blocks-code-block code-block\"><pre class=\"CodeMirror\" data-setting=\"{&quot;mode&quot;:&quot;clike&quot;,&quot;mime&quot;:&quot;text\/x-c++src&quot;,&quot;theme&quot;:&quot;material&quot;,&quot;lineNumbers&quot;:true,&quot;styleActiveLine&quot;:false,&quot;lineWrapping&quot;:false,&quot;readOnly&quot;:true,&quot;language&quot;:&quot;C++&quot;,&quot;modeName&quot;:&quot;cpp&quot;}\">#include&lt;bits\/stdc++.h&gt;\nusing namespace std;\n\n    class TreeNode{\n        public:\n        int val;\n        TreeNode* left;\n        TreeNode* right;\n\n        TreeNode(int x){\n            val = x;\n            left = NULL;\n            right = NULL;\n        }  \n    };\n\n    bool isSame(TreeNode* root, TreeNode* subRoot){\n        if(root==NULL &amp;&amp; subRoot==NULL) return true;\n        if(root==NULL || subRoot==NULL) return false;\n        if(root-&gt;val == subRoot-&gt;val) return isSame(root-&gt;left, subRoot-&gt;left) &amp;&amp; isSame(root-&gt;right,subRoot-&gt;right);\n        return false;\n    }\n    bool isSubtree(TreeNode* root, TreeNode* subRoot) {\n        if(root==NULL &amp;&amp; subRoot==NULL) return true;\n        if(root==NULL || subRoot==NULL) return false;\n        if(root-&gt;val == subRoot-&gt;val) {\n            \n            if(isSame(root, subRoot)) return true;\n        }\n        if(isSubtree(root-&gt;left,subRoot)) return true;\n        if(isSubtree(root-&gt;right,subRoot)) return true;\n        return false;\n    }\n\n\n    int main(){\n        TreeNode* root = new TreeNode(5);\n        root-&gt;left = new TreeNode(2);\n        root-&gt;right = new TreeNode(6);\n        root-&gt;left-&gt;left = new TreeNode(1);\n        root-&gt;left-&gt;right = new TreeNode(4);\n        root-&gt;left-&gt;right-&gt;left = new TreeNode(3);\n\n        TreeNode* subRoot = new TreeNode(2);\n        subRoot-&gt;left = new TreeNode(1);\n        subRoot-&gt;right = new TreeNode(4);\n        subRoot-&gt;right-&gt;left = new TreeNode(3);\n\n        bool ans = isSubtree(root, subRoot);\n        cout&lt;&lt;&quot;Is subRoot is a subtree of Root: &quot;;\n        (ans)? cout&lt;&lt;&quot;True&quot;: cout&lt;&lt;&quot;False&quot;;\n        return 0;\n    }<\/pre><\/div>\n\n\n\n<h3 class=\"wp-block-heading\"><strong>Java Code<\/strong><\/h3>\n\n\n\n<p>Here is the Java program for the recursive approach:<\/p>\n\n\n\n<div class=\"wp-block-codemirror-blocks-code-block code-block\"><pre class=\"CodeMirror\" data-setting=\"{&quot;mode&quot;:&quot;clike&quot;,&quot;mime&quot;:&quot;text\/x-java&quot;,&quot;theme&quot;:&quot;material&quot;,&quot;lineNumbers&quot;:true,&quot;styleActiveLine&quot;:false,&quot;lineWrapping&quot;:false,&quot;readOnly&quot;:true,&quot;language&quot;:&quot;Java&quot;,&quot;modeName&quot;:&quot;java&quot;}\">class TreeNode {\n    int val;\n    TreeNode left;\n    TreeNode right;\n\n    TreeNode(int x) {\n        val = x;\n        left = null;\n        right = null;\n    }\n}\n\nclass SubtreeCheck {\n    static boolean isSame(TreeNode root, TreeNode subRoot) {\n        if (root == null &amp;&amp; subRoot == null) return true;\n        if (root == null || subRoot == null) return false;\n        return root.val == subRoot.val &amp;&amp; isSame(root.left, subRoot.left) &amp;&amp; isSame(root.right, subRoot.right);\n    }\n\n    static boolean isSubtree(TreeNode root, TreeNode subRoot) {\n        if (root == null &amp;&amp; subRoot == null) return true;\n        if (root == null || subRoot == null) return false;\n        if (root.val == subRoot.val &amp;&amp; isSame(root, subRoot)) return true;\n        return isSubtree(root.left, subRoot) || isSubtree(root.right, subRoot);\n    }\n\n    public static void main(String[] args) {\n        TreeNode root = new TreeNode(5);\n        root.left = new TreeNode(2);\n        root.right = new TreeNode(6);\n        root.left.left = new TreeNode(1);\n        root.left.right = new TreeNode(4);\n        root.left.right.left = new TreeNode(3);\n\n        TreeNode subRoot = new TreeNode(2);\n        subRoot.left = new TreeNode(1);\n        subRoot.right = new TreeNode(4);\n        subRoot.right.left = new TreeNode(3);\n\n        boolean ans = isSubtree(root, subRoot);\n        System.out.print(&quot;Is subRoot is a subtree of Root: &quot;);\n        System.out.println(ans ? &quot;True&quot; : &quot;False&quot;);\n    }\n}<\/pre><\/div>\n\n\n\n<h3 class=\"wp-block-heading\"><strong>Python Code<\/strong><\/h3>\n\n\n\n<p>Here is the Python solution:<\/p>\n\n\n\n<div class=\"wp-block-codemirror-blocks-code-block code-block\"><pre class=\"CodeMirror\" data-setting=\"{&quot;mode&quot;:&quot;python&quot;,&quot;mime&quot;:&quot;text\/x-python&quot;,&quot;theme&quot;:&quot;material&quot;,&quot;lineNumbers&quot;:true,&quot;styleActiveLine&quot;:false,&quot;lineWrapping&quot;:false,&quot;readOnly&quot;:true,&quot;language&quot;:&quot;Python&quot;,&quot;modeName&quot;:&quot;python&quot;}\">class TreeNode:\n    def __init__(self, x):\n        self.val = x\n        self.left = None\n        self.right = None\n\ndef is_same(root, sub_root):\n    if not root and not sub_root:\n        return True\n    if not root or not sub_root:\n        return False\n    return root.val == sub_root.val and is_same(root.left, sub_root.left) and is_same(root.right, sub_root.right)\n\ndef is_subtree(root, sub_root):\n    if not root and not sub_root:\n        return True\n    if not root or not sub_root:\n        return False\n    if root.val == sub_root.val and is_same(root, sub_root):\n        return True\n    return is_subtree(root.left, sub_root) or is_subtree(root.right, sub_root)\n\nif __name__ == &quot;__main__&quot;:\n    root = TreeNode(5)\n    root.left = TreeNode(2)\n    root.right = TreeNode(6)\n    root.left.left = TreeNode(1)\n    root.left.right = TreeNode(4)\n    root.left.right.left = TreeNode(3)\n\n    sub_root = TreeNode(2)\n    sub_root.left = TreeNode(1)\n    sub_root.right = TreeNode(4)\n    sub_root.right.left = TreeNode(3)\n\n    ans = is_subtree(root, sub_root)\n    print(&quot;Is subRoot is a subtree of Root:&quot;, ans)<\/pre><\/div>\n\n\n\n<p><strong>Output:<\/strong>&nbsp;<\/p>\n\n\n\n<pre class=\"wp-block-code has-black-color has-text-color has-background has-link-color wp-elements-88a8085cad6e3507430b624b423b6340\" style=\"background-color:#fedcba\"><code>Is subRoot is a subtree of Root: True<\/code><\/pre>\n\n\n\n<p>The time complexity to check if a binary tree is a subtree of another tree is O(n*m) where n is the number of nodes in a tree and m is several nodes in a subtree. The space complexity is O(1) as we are not using any extra space.\u00a0<\/p>\n\n\n\n<h2 class=\"wp-block-heading\"><strong>Conclusion<\/strong><\/h2>\n\n\n\n<p>In this article, we solved &#8216;Subtree of Another Tree&#8217; problem from <a href=\"https:\/\/leetcode.com\/problems\/subtree-of-another-tree\/description\/\" target=\"_blank\" rel=\"noreferrer noopener nofollow\">leetcode<\/a>. We saw how we can recursively approach this problem. In this article, we used classes. If you don\u2019t know about <a href=\"https:\/\/favtutor.com\/blogs\/java-array-of-objects\">classes<\/a> try to learn them first. <\/p>\n","protected":false},"excerpt":{"rendered":"<p>Understand the Subtree of Another Tree problem using the recursive approach, with implementation in C++, Java, and Python.<\/p>\n","protected":false},"author":14,"featured_media":2040,"comment_status":"closed","ping_status":"closed","sticky":false,"template":"","format":"standard","meta":{"jnews-multi-image_gallery":[],"jnews_single_post":null,"jnews_primary_category":{"id":"","hide":""},"footnotes":""},"categories":[7],"tags":[105,14,15],"class_list":["post-1955","post","type-post","status-publish","format-standard","has-post-thumbnail","hentry","category-data-structures-algorithms","tag-binary-tree","tag-dsa","tag-leetcode"],"_links":{"self":[{"href":"https:\/\/favtutor.com\/articles\/wp-json\/wp\/v2\/posts\/1955","targetHints":{"allow":["GET"]}}],"collection":[{"href":"https:\/\/favtutor.com\/articles\/wp-json\/wp\/v2\/posts"}],"about":[{"href":"https:\/\/favtutor.com\/articles\/wp-json\/wp\/v2\/types\/post"}],"author":[{"embeddable":true,"href":"https:\/\/favtutor.com\/articles\/wp-json\/wp\/v2\/users\/14"}],"replies":[{"embeddable":true,"href":"https:\/\/favtutor.com\/articles\/wp-json\/wp\/v2\/comments?post=1955"}],"version-history":[{"count":8,"href":"https:\/\/favtutor.com\/articles\/wp-json\/wp\/v2\/posts\/1955\/revisions"}],"predecessor-version":[{"id":2405,"href":"https:\/\/favtutor.com\/articles\/wp-json\/wp\/v2\/posts\/1955\/revisions\/2405"}],"wp:featuredmedia":[{"embeddable":true,"href":"https:\/\/favtutor.com\/articles\/wp-json\/wp\/v2\/media\/2040"}],"wp:attachment":[{"href":"https:\/\/favtutor.com\/articles\/wp-json\/wp\/v2\/media?parent=1955"}],"wp:term":[{"taxonomy":"category","embeddable":true,"href":"https:\/\/favtutor.com\/articles\/wp-json\/wp\/v2\/categories?post=1955"},{"taxonomy":"post_tag","embeddable":true,"href":"https:\/\/favtutor.com\/articles\/wp-json\/wp\/v2\/tags?post=1955"}],"curies":[{"name":"wp","href":"https:\/\/api.w.org\/{rel}","templated":true}]}}