Duplicate subtree in Binary Tree | Practice | GeeksforGeeks

Given a binary tree, find out whether it contains a duplicate sub-tree of size two or more, or not.

Example 1 :
Input : 
               1
             /   \ 
           2       3
         /   \       \    
        4     5       2     
                     /  \    
                    4    5
Output : 1
Explanation : 
    2     
  /   \    
 4     5
is the duplicate sub-tree.
Example 2 :
Input : 
               1
             /   \ 
           2       3
Output: 0
Explanation: There is no duplicate sub-tree 
in the given binary tree.

Your Task:  
You don't need to read input or print anything. Your task is to complete the function dupSub() which takes root of the tree as the only arguement and returns 1 if the binary tree contains a duplicate sub-tree of size two or more, else 0.
Note: Two same leaf nodes are not considered as subtree as size of a leaf node is one.

Constraints:
1 ≤ length of string ≤ 100
 
0
joyrockok1 week ago
class Solution {ArrayList<ArrayList<Integer>> arrayList;   int dupSub(Node root) {       // code here    arrayList = new ArrayList<ArrayList<Integer>>();    ArrayList<Integer> subList = new ArrayList<Integer>();        if(root == null) return 0;        subList.add(root.data);        if(root.left != null) {     subList.add(root.left.data);    }        if(root.right != null) {     subList.add(root.right.data);    }        if(subList.size() > 3) return 0;        if(subList.size() == 3) {     arrayList.add(subList);    }     int left = dupSubTree(root.left); int right = dupSubTree(root.right);        if(left == 1 || right == 1) return 1;        return 0;   }      int dupSubTree(Node node) {    ArrayList<Integer> subList = new ArrayList<Integer>();        if(node == null) return 0;        subList.add(node.data);        if(node.left != null) {     subList.add(node.left.data);    }        if(node.right != null) {     subList.add(node.right.data);    }        if(subList.size() == 3 && arrayList.contains(subList)) {     return 1;    }        if(subList.size() == 3) {     arrayList.add(subList);    }        int left = dupSubTree(node.left);    int right = dupSubTree(node.right);        if(left == 1 || right == 1) return 1;        return 0;   }   }
0
goelyash2 weeks ago
    map<int,pair<int,int>>m;
    void inorder(Node* root,bool &flag){
        if(!root)return;
        inorder(root->left,flag);
        int l= (root->left)?root->left->data:-1;
        int r= (root->right)?root->right->data:-1;
        if(m[root->data].first==l && l!=-1 && r!=-1 && m[root->data].second==r){flag=true;return;}
        m[root->data]={l,r};
        inorder(root->right,flag);

    }
    int dupSub(Node *root) {
        vector<int>in;
        bool flag=false;
        inorder(root,flag);
        if(flag==true)return 1;
        else return 0;
    }
-1
hydracody453 weeks ago
upvote:
unordered_set<string> aa;
    int ans=0;
    string hh(Node* r){
        if(r==NULL || ans==1){
            return "";
        }
        string st;
        st=r->data +hh(r->left)+hh(r->right);
        if(st.size()>1 && aa.count(st)>0){//size two or more, or not.
            ans=1;
            return "";
        }
        aa.insert(st);
        return st;
    }
    int dupSub(Node *root) {
         // code here
         hh(root);
         return ans;
    }
0
palashsarkar00073 weeks ago
'''class Node:   def _init_(self,val):       self.data = val       self.left = None       self.right = None'''
class Solution:   def __dupSubHelper (self, root):       if (root == None): return [], False       if ((root.left == None) and (root.right == None)): return [str(root.data)], False       left_lst, right_lst = [], []       left_state, right_state = False, False       tmp_str = ''       if (root.left != None):           left_lst, left_state = self.__dupSubHelper(root.left)           if (left_state): return left_lst, left_state       if (root.right != None):           right_lst, right_state = self.__dupSubHelper(root.right)           if (right_state): return right_lst, right_state       left_lst.append(str(root.data)) ; left_lst.extend(right_lst) ; tmp_str = ''.join(left_lst)       if (tmp_str in self.seen_before): return left_lst, True       self.seen_before.add(tmp_str)       return left_lst, False
   def dupSub (self, root):       self.seen_before = set()       return 1 if self.__dupSubHelper(root)[1] else 0
-1
ahmadsahil261 month ago
// JAVA Solution
class Solution {   boolean check = false;      String solve(Node root,Set<String> set){              if(root==null)           return "";              String left = solve(root.left,set);       String right = solve(root.right,set);       String temp = left+root.data+right;       String t = Integer.toString(root.data);       if((temp.length()>t.length()&&temp.length()>=2)&&set.contains(temp)){           check = true;       }       else if(temp.length()>t.length()){           set.add(temp);       }       return temp;   }         int dupSub(Node root) {       // code here        Set<String> set = new HashSet<>();              solve(root,set);              return check==true?1:0;                        }}
0
harrypotter01 month ago
## Duplicate subtree in Binary Tree
def solve(root,s):
if not root:
return False

if not root.left and not root.right:
return False

st = ""

 
if root.left:
st+= chr(root.left.data)
else:
st+= "$"

st+= chr(root.data)


 
if root.right:
st+= chr(root.right.data)
else:
st+= "$"

 
if st in s and '$' not in st:
# print(st)
return True
else:
s.add(st)
return solve(root.left,s) or solve(root.right,s)


 
class Solution:
def dupSub(self, root):
s = set()

if solve(root, s):
# print(s)
return 1
else:
# print(s)
return 0

 
0
sfazal0001 month ago
unordered_map<string,int>m;
string solve(node* root){   if(root == NULL)   {       return "$";   }      string s =" ";      if(!root->right and !root->left)   {        s = to_string(root->data);                return s;   }      s= s+to_string(root->data);   s = s+solve(root->left);   s = s+solve(root->right);      m[s]++;   return s;}                  
 
bool checkDuplicates(node* root){   solve(root);      for(auto x : m)   {          if(x.second >=2 )          {                            return true;          }   }      return false;             }      
0
codecrackerp2 months ago
void trav(Node*root,vector<int>&v){
       if(root==NULL)return;
       v.push_back(root->data);
       trav(root->left,v);
       trav(root->right,v);
   }
   int dupSub(Node *root) {
       if(root==NULL)return 0;
       queue<Node*>q;
       q.push(root);
       map<vector<int>,int>vc;
       while(!q.empty()){
           Node*frnt=q.front();
           q.pop();
           vector<int>v;
           trav(frnt,v);
           if(v.size()>=2){
               vc[v]++;
               if(vc[v]==2)return 1;
           }
           if(frnt->left!=NULL){
               q.push(frnt->left);
           }
           if(frnt->right!=NULL){
               q.push(frnt->right);
           }
       }
       return 0;
   }
+4
sanketbhagat2 months ago
SIMPLE JAVA SOLUTION
class Solution {
    
    String solve(Node root, Map<String, Integer> map){
        if(root==null) return "";
        String str = solve(root.left,map)+"#"+root.data+"#"+solve(root.right,map);
        if(root.left!=null || root.right!=null) map.put(str,map.getOrDefault(str,0)+1);
        return str;
    }
    
    int dupSub(Node root) {
        // code here
        Map<String, Integer> map = new HashMap<>();
        solve(root,map);
        for(Map.Entry<String,Integer> e: map.entrySet()){
            if(e.getValue()>1) return 1;
        }
        return 0;
    }
}
0
shashikantg2 months ago
 unordered_set<string> st;
    int ans=0;
    string helper(Node * root){
        if(root==NULL || ans==1) return "";
        string s1=helper(root->left) + root->data + helper(root->right);
        if(s1.size()>1 && st.count(s1)>0){
            ans=1; return "";
        }
        st.insert(s1);
        return s1;
    }
    
    int dupSub(Node *root) {
         helper(root);
         return ans;
         
    }
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.