Output: 70 Explanation: 105 - 50 = 55 (As 105 and 50 nodes are siblings) 75 - 5 = 70 (As 75 and 5 nodes are siblings) 106 - 101 = 5 (As 106 and 5 nodes are siblings) Other than these, there is no other pair of nodes that are siblings. So among them the max difference is 70. (75 - 5 = 70)
Output: 60 Explanation: 120 - 60 = 60 90 - 45 = 45 160 - 110 = 50 Other than these, there is no other pair of nodes that are siblings. So among them the max difference is 60. (120 - 60 = 60)
Approach:
The basic Idea is to check whether the nodes are siblings or not if sibling then find out the maximum difference.
Follow the steps mentioned below to implement the idea:
Iterate the BST in the preorder fashion. Root Left Right.
At every point,
Check if the left and right children are available.
If both are available, then calculate the difference between the right and left values. (By default BST right val > left val)
Maximize the absolute maximum difference.
Else just continue the traversal.
After the traversal ends, return the maximum difference between the sibling nodes.
Below is the Implementation of the above approach: