GeeksforGeeks » Interview Questions

Adobe Interview Question for Software Engineer/Developer (Fresher) about Algorithms, Aptitiude, C++,

(4 posts)
  1. Shubhra
    guest
    Posted 4 months ago #

    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.

  2. Shantanu
    guest
    Posted 4 months ago #

    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)

  3. beacon
    guest
    Posted 4 months ago #

    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

  4. 5050
    Member
    Posted 2 months ago #

    its wrong solution i think ....


Reply

You must log in to post.

RSS feed for this topic