Check if subtree | Practice | GeeksforGeeks

Given two binary trees with head reference as T and S having at most N nodes. The task is to check if S is present as subtree in T.
A subtree of a tree T1 is a tree T2 consisting of a node in T1 and all of its descendants in T1.
Example 1:
Input:
T:      1          S:   3
      /   \            /
     2     3          4
   /  \    /
  N    N  4
Output: 1 
Explanation: S is present in T


Example 2:
Input:
T:      26         S:   26
       /   \           /  \
     10     N        10    N
   /    \           /  \
   20    30        20  30
  /  \            /  \
 40   60         40  60
Output: 1 
Explanation: 
S and T are both same. Hence, 
it can be said that S is a subtree 
of T.

Your Task:
You don't need to read input or print anything. Your task is to complete the function isSubtree() that takes root node of S and T as parameters and returns 1 if S is a subtree of T else 0.
Note: The nodes can have the duplicate values.

Expected Time Complexity: O(N).
Expected Auxiliary Space: O(N).
Constraints:
1 <= Number of nodes <= 105
1 <= Value of nodes <= 104
 
0
devanshuz3 days ago
0.69 JAVA Solution 10 Lines
public static boolean isSubtree(Node T, Node S) {
        if (T == null) return false;
        if (isIdentical(T, S))
            return true;
        return isSubtree(T.left, S) || isSubtree(T.right, S);
    }
    
    public static boolean isIdentical(Node T, Node S){
        if (T == null || S == null){
            return T == S;
        }
        return T.data == S.data && isIdentical(T.left, S.left) && isIdentical(T.right, S.right);
    }
+1
shubham211019971 week ago
static boolean helper(Node r1,Node r2){
       if(r1==null&& r2==null)return true;
          if(r1==null||r2==null)return false;
       return ((r1.data==r2.data)&&helper(r1.left,r2.left)&&helper(r1.right,r2.right));
   }
   public static boolean isSubtree(Node r1, Node r2) {
        if(r1==null && r2==null)return true;
        if(r1==null&&r2!=null)return false;
        return (helper(r1,r2)||isSubtree(r1.left,r2)||isSubtree(r1.right,r2));
        
   }
0
aayushwas1 week ago
0.78/1.95 C++
//aretreessame checks if two trees are same
	bool aretreessame(Node* t, Node* s){
        if(t==NULL&&s!=NULL || t!=NULL&&s==NULL) 						  return false;
        if(t==NULL&&s==NULL) return true;
        if(t->data!=s->data) return false;
        bool a = aretreessame(t->left,s->left);
        bool b = aretreessame(t->right,s->right);
        
        return a&&b;
    }
// checks if s subtree exists in T   
    bool isSubTree(Node* T, Node* S) 
    {
        if(T==NULL&&S!=NULL || T!=NULL&&S==NULL) return false;
        if(T==NULL&&S==NULL) return true;
        
        if(T->data==S->data&&aretreessame(T,S)==true){
            return true;
        }
        bool l = isSubTree(T->left,S);
        bool r = isSubTree(T->right,S);
        return l||r;
        
    }
+1
tarunkanade2 weeks ago
0.69/1.94 Java O(n), O(h) with explanation
public static boolean isSubtree(Node T, Node S) {
        // add code here.
        if(T == null){
            return false;
        }
        
        if(T.data == S.data){
            //     3
            //    / \
            //   3   5
            //  / \
            // 4   6      for eg: this is "T"
            // and we want to find:
            //     3
            //    / \
            //   4   6
            // As here 3 is present 2 times in T, and "S" is the subtree with
            // root as 3 which is the later one (in T) we can see from the visualization
            // so in such conditions if we simply return checkIfSame(T, S)
            // then our code will not check subsequent subtrees after the first
            // encounter with 3 (in T) and will return false as a result which is wrong
            // So for keep searching the subtrees we are again checking if 
            // checkIfSame(T, S) == true then only return (true) otherwise keep searching
            if(checkIfSame(T, S)){
                return true;
            }
        }
        
        if(isSubtree(T.left, S) == true || isSubtree(T.right, S) == true){
            return true;
        }
        else{
            return false;
        }
    }
    
    // method for checking if 2 trees are identical
    private static boolean checkIfSame(Node root1, Node root2){
        if(root1 == null && root2 == null){
            return true;
        }
        else if((root1 == null && root2 != null) || (root1 != null && root2 == null)){
            return false;
        }
        else if(root1.data != root2.data){
            return false;
        }
        else{
            if(checkIfSame(root1.left, root2.left) == true && 
                    checkIfSame(root1.right, root2.right) == true){
                return true;
            }
            else{
                return false;
            }
        }
    }
+3
akashkhurana283 weeks ago
JAVA SOLUTION
class Solution {      public static boolean check(Node root,Node subroot)  {      if(root==null && subroot==null)      {          return true;      }      if(root==null || subroot==null)      {          return false;      }      if(root.data==subroot.data)      {  return check(root.left,subroot.left) && check(root.right,subroot.right);      }      return false;  }   public static boolean isSubtree(Node T, Node S) {       // add code here.   if(S==null)      {          return true;      }      if(T==null)      {          return false;      }            if(T.data==S.data)      {         if(check(T,S))         {             return true;         }      }            return isSubtree(T.left,S) || isSubtree(T.right,S);    }}
0
mohit negi3 weeks ago
c++ simple solution  O(N)   int checkSub(Node *t,Node *s)   {       if(t==NULL && s==NULL) return 1;       if(!t||!s) return 0;       if(t->data!=s->data) return 0;       else           { int a=checkSub(t->left,s->left);              int b=checkSub(t->right,s->right);              return a&b;           }              }      void check(Node* t, Node* s,int &is)   {       if(t==NULL) return;       else if(!is)       {   if(t->data==s->data)           {               is= checkSub(t,s);               if(is) return;           }           check(t->left,s,is);           check(t->right,s,is);       }   }         bool isSubTree(Node* T, Node* S)    {      int is=0;      check(T,S,is);      return is;               }
0
himanshujain4573 weeks ago
No rocket Science:Simple Solution
class Solution {   static void storeRoot(Node r,Node s,  ArrayList<Node>ans){       if(r==null)return ;       if(r.data==s.data)       ans.add(r);       storeRoot(r.left,s,ans);       storeRoot(r.right,s,ans);   }   static boolean check(Node r,Node s){       if(r==null&&s==null)return true;       if(r==null &&s!=null)return false;       if(r!=null&&s==null)return false;       if(r.data!=s.data)return false;       if(check(r.left,s.left)&&check(r.right,s.right))return true;       return false;   }   public static boolean isSubtree(Node T, Node S) {      ArrayList<Node>ans=new ArrayList<>();      if(T==null&&S==null)return true;      if(T==null&&S!=null)return false;      if(T!=null &&S==null)return true;      storeRoot(T,S,ans);      for(Node e:ans){          if(check(e,S))          return true;      }      return false;   }}
0
nikhilchakravarthy091 month ago
void findSubTreeNode(Node* t, Node* s,vector<Node*>& temp){
        if(t==NULL) return;
        if(t->data == s->data) temp.push_back(t);
        findSubTreeNode(t->left,s,temp);
        findSubTreeNode(t->right,s,temp);
    }
    bool checkSubTree(Node* sub, Node* s){
        if(s==NULL && sub==NULL) return true;
        if((sub==NULL && s!=NULL) || (sub!=NULL && s==NULL))return false;
        if(sub->data == s->data){
            return (checkSubTree(sub->left,s->left) && checkSubTree(sub->right,s->right)); 
        }
        return false;
    }
    bool isSubTree(Node* T, Node* S) 
    {
        Node* sub=NULL;
        vector<Node*> temp;
        findSubTreeNode(T,S,temp);
        
        for(int i=0;i<temp.size();i++)
            if (checkSubTree(temp[i],S)) return true;
            return false;
    }
0
harrypotter02 months ago
    def isSubTree(self, s, t):
       def convert(p):
           return "^" + str(p.data) + "#" + convert(p.left) + convert(p.right) if p else "$"
       
       return convert(t) in convert(s)

0
adityapratapsingh0820172 months ago
python solution not accepted why?
class Solution:
    def isSubTree(self, T, S):
        # Code here
        if not T:
            return False
        if not S:
            return True
        if mirror(T,S):
            return True
        return (self.isSubTree(T.left,S) or self.isSubTree(T.right,S))


def mirror(t,s):
    if not s or not t:
        return t==s
    return (t.data==s.data) and mirror(t.left,s.left) and mirror(t.right,s.right)
We strongly recommend solving this problem on your own before viewing its editorial. Do you still
                    want to view the editorial?
 Login to access your submissions. 

Problem


Contest

Reset the IDE using the second button on the top right corner.
Avoid using static/global variables in your code as your code is tested against multiple test cases and these tend to retain their previous values.
Passing the Sample/Custom Test cases does not guarantee the correctness of code. On submission, your code is tested against multiple test cases consisting of all possible corner cases and stress constraints.
You can access the hints to get an idea about what is expected of you as well as the final solution code.
You can view the solutions submitted by other users from the submission tab.