Problem:
You have two very large binary trees: T1, with millions of nodes, and T2, with hundreds of nodes Create an algorithm to decide if T2 is a subtree of T1
Solution:
You have two very large binary trees: T1, with millions of nodes, and T2, with hundreds of nodes Create an algorithm to decide if T2 is a subtree of T1
Solution:
- Traverse the Tree T1.
- For each node, call a method to do the following (Step 3),
- traverse both the Tree T1 and T2, until tree T2 exhausts or until data of T1 and T2 does not match.
- Return true if T2 is a subtree of T1 else return false.
Complexity: O(m*n) in the worst case
Code:
Code:
No comments:
Post a Comment