One TC is failing and that is also not completely visible on the GFG platform. I want to know whether the code is correct or not and if WRONG, where is the logic going wrong?
Logic: Just checking inorder and preorder of both trees and checking whether it is a subset or not!
P.S. Please don’t provide me GFG article links of the same question. This is my own approach and I want help regarding this only.
This is my approach:
If all vertices are distinct ( which should be )
Then just find the vertex in the big tree which is equal to root of small tree ( if vertex not found then that is not a subtree )
So you got the starting points of the both the tree and now you need to compare
Just apply level order traversal simultaneously if at a point any node differs until level order of small tree is completed then it will not be a subtree
(by vertex i mean node)
If vertices are not distinct then complexity will be O(v^2) as you have to check every node as a starting possibility which is very inefficient obviously
In a Binary Search Tree (BST), all keys in left subtree of a key must be smaller and all keys in right subtree must be greater. So a Binary Search Tree by definition has distinct keys and duplicates in binary search tree are not allowed.
See if you find preorder and inorder of both trees then the subtree’s pre and inorder will be subset somewhere in pre and inorder of larger tree @akshitm16
I see you haven’t read the full article. Read the whole thing and and my test case as well. The article also mentions a similar tc as mine where your logic would fail and its possible solution.