![]() |
VOOZH | about |
Given a Binary tree, The task is to find the maximum value by subtracting the value of node B from the value of node A, where A and B are two nodes of the binary tree and A is an ancestor of B.
Examples:
Input:
Output: 7
Explanation: We can have various ancestor-node difference, some of which are given below :
8 β 3 = 5 , 3 β 7 = -4, 8 β 1 = 7, 10 β 13 = -3
Among all those differences maximum value is 7 obtained by subtracting 1 from 8, which we need to return as result.Input:
9
/ \
6 3
/ \
1 4
Output: 8
Approach:
Traverse whole binary tree to get max difference and we can obtain the result in one traversal only by following below steps :
- If current node is a leaf node then just return its value because it canβt be ancestor of any node.
- Then at each internal node try to get minimum value from left subtree and right subtree and calculate the difference between node value and this minimum value and according to that update the result.
Follow the below steps to Implement the idea:
Below is the implementation of the above idea.
7
Time Complexity: O(N), for visiting every node of the tree.
Auxiliary Space: O(N) for recursion call stack.