03. Brothers From Different Roots
The problem can be found at the following link: Question Link
My Approach
This question is another apllication of BST property of inordere traversal. So for solving this,
I use in-order traversals of both trees to obtain sorted arrays
t1
andt2
.Then, I iterate through these arrays with two pointers, comparing the sum of elements at the pointers with the target
x
. Based on the comparison, I adjust the pointers to find pairs that sum tox
.
Time and Auxiliary Space Complexity
Time Complexity:
O(N + M)
, whereN
andM
are the numbers of nodes in the two trees.Auxiliary Space Complexity:
O(N + M)
, as we store in-order traversals in arrays.
Code (C++)
Contribution and Support
For discussions, questions, or doubts related to this solution, please visit our discussion section. We welcome your input and aim to foster a collaborative learning environment.
If you find this solution helpful, consider supporting us by giving a ⭐ star to the getlost01/gfg-potd repository.
Last updated