Input:5 / \ 6 5 \ \ 6 5
Diagonal 6 – 6 and 5 – 5 contains equal value.
Therefore, the required output is 2.
Input:5 / \ 6 5 \ \ 5 5
- Traverse the given binary tree in a diagonal order and store the starting node of each diagonal as the key and for each key, store all the values in that diagonal in a Hashset.
- After the traversal, find the number of keys having size of the set equal to 1 and print it as the answer.
Below is the implementation of the above approach.
Time Complexity: O(N)
Auxiliary Space: O(N)
Attention reader! Don’t stop learning now. Get hold of all the important mathematical concepts for competitive programming with the Essential Maths for CP Course at a student-friendly price. To complete your preparation from learning a language to DS Algo and many more, please refer Complete Interview Preparation Course.