In: Computer Science
3. Assume that binary trees are defined as
public class BTNode<E>
{
private E data;
private BTNode<E> left, right;
}
We say that a binary tree t1 is a prefix of a binary tree t2 if t2 can be made identical to t1
by removing zero or more leaves of t2. Write a method
The best way i can think of for this problem is, comparing leaves of two trees and storing leaves beforehand
Now lets see an example, suppose, tree t1 has
A, b, c, d, e leaves in this order from left ro right, store them in a SET
Also, tree t2 has leaves
Now you just traverse the tree t2 and whenever you come across a leaf, you just check in same order as in t1 set,
Lets say, i is pinting on leaf b in t1
But while traversing, in t2 leaf j comes, but expected leaf was b, so you just make this leaf as null there itslef, you dont need it
The best part of algorithmi is its Time Complexity,
For finding leaves, it will take linear time O(N), nis number of nodes in tree
For traversing also linear time,
But can you guess what about comparing,
Its constant, O(1), as we are maintaining a pointer on t1 set, which increments after every successful comparison
Now i believe you got the algorithm, tell this to anyone, and he or she will be impressed.
As you learned how to think about a problem.
Note : writing code isnt, hard even GOOGLE nevet asks in interview to code necessarily, you need to have problem solving skills, and you learned a bit today.
I hope, this must have helped you.
Happy learning.