GeeksforGeeks » Interview Questions
Adobe Interview Question for Software Engineer/Developer (Fresher) about Algorithms, Aptitiude, C++,
(4 posts)-
Given 2 trees A and B find if tree B is a subtree of Tree A or not. Provide the most optimized solution that you can think of.
-
how about this:
Conduct a DFS or a BFS on A. Match address each node you encounter against address of root of B. Since the content at an address can not have 2 different definitions, the moment you have a match, you can conclude you found B in A. if search completes, B is not in A. complexity, O(n) -
public boolean isSubtree(Node b){ return isSubtree(this.getRoot(), b); } private boolean isSubtree(Node compareTo, Node b){ if((compareTo!=null)&&(b!=null)){ if(compareTo.data() == b.data()) return (this.isSubtree(compareTo.left(), b.left()))&&(this.isSubtree(compareTo.right(), b.right())); else return this.isSubtree(compareTo.left(), b) || (isSubtree(compareTo.right(), b)); } else { return (compareTo == null)&&(b == null); } }PS:bhuvnesh.agrawal.27@gmail
-
its wrong solution i think ....
Reply
You must log in to post.