0% completed
Time and Space complexity in the solution is incorrect?
Run Qi Jack Li
Oct 31, 2024
Time Complexity:
The goal of merging two binary trees involves visiting every node in both trees where nodes exist. Therefore, we need to account for all nodes in the larger of the two trees (t1 and t2), not the smaller.
If one tree is smaller than the other and does not reach the depth of the other tree, we still traverse down the structure of the larger tree, filling in nodes as needed. Hence, the time complexity is determined by the larger tree, or O(max(m, n)), not O(min(m, n)).
Space Complexity:
The space complexity also depends on the depth of the recursion (i.e., the height of the deeper tree) and the total nodes in the new merged tree.
Recursive Stack: If k is the height of the deeper tree between t1 and t2, the recursive stack will go as deep as k. Thus, the space complexity for the recursion stack is O(k), where k = max(height(t1), height(t2)).
5
0
Comments
Mykola Zhadanova year ago
Hi, Run Qi Jack Li. It's not exactly like this - we don't need to visit all nodes in larger tree. To perform merge, we need to visit only those nodes, which are not empty in both trees at same positions. We can do this, for example, using pre-order tree traversal (curre...
On this page