Maximum difference between a node and its descendant

Posted: 12 Jul, 2020
Difficulty: Moderate

PROBLEM STATEMENT

Try Problem

Given a binary tree, find the maximum difference between the values of two nodes 'A' and 'B' where 'A' is an ancestor of 'B'.

Note :
A node that is connected to all lower-level nodes is called an "ancestor". The connected lower-level nodes are descendants of the ancestor node.
Input format :
Elements in the level order form. The input consists of values of nodes separated by a single space in a single line. In case a node is null, we take -1 on its place.

For example, the input for the tree depicted in the below image would be :

alt text

1
2 3
4 -1 5 6
-1 7 -1 -1 -1 -1
-1 -1

Explanation :

Level 1 :
The root node of the tree is 1

Level 2 :
Left child of 1 = 2
Right child of 1 = 3

Level 3 :
Left child of 2 = 4
Right child of 2 = null (-1)
Left child of 3 = 5
Right child of 3 = 6

Level 4 :
Left child of 4 = null (-1)
Right child of 4 = 7
Left child of 5 = null (-1)
Right child of 5 = null (-1)
Left child of 6 = null (-1)
Right child of 6 = null (-1)

Level 5 :
Left child of 7 = null (-1)
Right child of 7 = null (-1)

The first not-null node (of the previous level) is treated as the parent of the first two nodes of the current level. The second not-null node (of the previous level) is treated as the parent node for the next two nodes of the current level and so on.
The input ends when all nodes at the last level are null (-1).
Note :
The above format was just to provide clarity on how the input is formed for a given tree. 
The sequence will be put together in a single line separated by a single space. Hence, for the above depicted tree, the input will be given as:

1 2 3 4 -1 5 6 -1 7 -1 -1 -1 -1 -1 -1
Output Format :
The maximum difference of the nodes.
Note
You are not required to print anything, and it has already been taken care of. Just implement the function.
Constraints :
0 <= Number of nodes <= 10^7
0 <= Value of node <= 10^8

Timi Limit: 1sec
Approach 1

We can solve this question by traversing tree one time and using recursion to find 3 values; the maximum element, the minimum element, and the maximum difference. Here is the algorithm:

1. If we are at a leaf node, then we'll just return 0 because it can’t be an ancestor of any node. 

2. Then at each internal or inner node of the tree, we will update the maximum and minimum values (initially INT_MIN and INT_MAX respectively) according to the node's data and calculate the max difference as (maximum - minimum)

Then using recursion, we will find the max difference of the left and right subtrees. 

The final max difference for the current node will then be maximum of the three individual max differences, i.e. the difference between maximum and minimum, the max difference for the left subtree and the max difference for the right subtree.

Try Problem