Related Articles
Count diagonal paths from a node to a leaf consisting of same valued nodes
• Last Updated : 17 Feb, 2021

Given a Binary Tree, the task is to find the count of diagonal paths to the leaf of a binary tree such that values of all the nodes on the same diagonal are equal.

Examples:

Input:

```       5
/ \
6   5
\   \
6   5```

Output:
Explanation:
Diagonal 6 – 6 and 5 – 5 contains equal value.
Therefore, the required output is 2.

Input:

```       5
/ \
6   5
\   \
5   5```

Output: 1

Approach: The main idea is to traverse the tree diagonally using a Map. Follow the steps below to solve this problem:

Below is the implementation of the above approach.

## C++14

 `// C++ program of the above approach``#include ``using` `namespace` `std;` `struct` `TreeNode``{``    ``int` `val = 0;``    ``TreeNode *left, *right;``    ` `    ``TreeNode(``int` `x)``    ``{``        ``val = x;``        ``left = NULL;``        ``right = NULL;``    ``}``};` `// Function to perform diagonal``// traversal on the given binary tree``void` `fillMap(TreeNode *root, ``int` `left,``             ``map<``int``, set<``int``>> &diag)``{``    ` `    ``// If tree is empty``    ``if` `(!root)``        ``return``;` `    ``// If current diagonal is not visited``    ``if` `(diag[left].size() == 0)``    ``{``        ` `        ``// Update diag[left]``        ``diag[left].insert(root->val);``    ``}``    ` `    ``// Otherwise, map current node``    ``// with its diagonal``    ``else``        ``diag[left].insert(root->val);` `    ``// Recursively, traverse left subtree``    ``fillMap(root->left, left + 1, diag);` `    ``// Recursively, traverse right subtree``    ``fillMap(root->right, left, diag);``}` `// Function to count diagonal``// paths having same-valued nodes``int` `sameDiag(TreeNode *root)``{``    ` `    ``// Maps the values of all``    ``// nodes with its diagonal``    ``map<``int``, set<``int``>> diag;` `    ``// Stores indexing of diagonal``    ``int` `left = 0;` `    ``// Function call to perform``    ``// diagonal traversal``    ``fillMap(root, left, diag);` `    ``// Stores count of diagonals such``    ``// that all the nodes on the same``    ``// diagonal are equal``    ``int` `count = 0;` `    ``// Traverse each diagonal``    ``for``(``auto` `d : diag)``    ``{``        ` `        ``// If all nodes on the current``        ``// diagonal are equal``        ``if` `(diag[d.first].size() == 1)``        ` `            ``// Update count``            ``count += 1;``    ``}``    ``return` `count;``}` `// Driver Code``int` `main()``{``    ` `    ``// Given tree``    ``TreeNode *root = ``new` `TreeNode(5);``    ``root->left = ``new` `TreeNode(6);``    ``root->right = ``new` `TreeNode(5);``    ``root->left->right = ``new` `TreeNode(6);``    ``root->right->right = ``new` `TreeNode(5);``    ` `    ``// Function call``    ``cout << sameDiag(root);``}` `// This code is contributed by mohit kumar 29`

## Java

 `// Java program for above approach``import` `java.util.*;``import` `java.lang.*;``class` `GFG``{` `  ``// Structure of a Node``  ``static` `class` `TreeNode``  ``{``    ``int` `val;``    ``TreeNode left, right;` `    ``TreeNode(``int` `key)``    ``{``      ``val = key;``      ``left = ``null``;``      ``right = ``null``;``    ``}``  ``};` `  ``// Function to perform diagonal``  ``// traversal on the given binary tree``  ``static` `void` `fillMap(TreeNode root, ``int` `left,``                      ``Map> diag)``  ``{` `    ``// If tree is empty``    ``if` `(root == ``null``)``      ``return``;` `    ``// If current diagonal is not visited``    ``if` `(diag.get(left) == ``null``)``    ``{` `      ``// Update diag[left]``      ``diag.put(left, ``new` `HashSet());``      ``diag.get(left).add(root.val);``    ``}` `    ``// Otherwise, map current node``    ``// with its diagonal``    ``else``      ``diag.get(left).add(root.val);` `    ``// Recursively, traverse left subtree``    ``fillMap(root.left, left + ``1``, diag);` `    ``// Recursively, traverse right subtree``    ``fillMap(root.right, left, diag);``  ``}` `  ``// Function to count diagonal``  ``// paths having same-valued nodes``  ``static` `int` `sameDiag(TreeNode root)``  ``{` `    ``// Maps the values of all``    ``// nodes with its diagonal``    ``Map> diag = ``new` `HashMap<>();` `    ``// Stores indexing of diagonal``    ``int` `left = ``0``;` `    ``// Function call to perform``    ``// diagonal traversal``    ``fillMap(root, left, diag);` `    ``// Stores count of diagonals such``    ``// that all the nodes on the same``    ``// diagonal are equal``    ``int` `count = ``0``;` `    ``// Traverse each diagonal``    ``for``(Map.Entry> d:diag.entrySet())``    ``{` `      ``// If all nodes on the current``      ``// diagonal are equal``      ``if` `(d.getValue().size() == ``1``)` `        ``// Update count``        ``count += ``1``;``    ``}``    ``return` `count;``  ``}` `  ``// Driver function``  ``public` `static` `void` `main (String[] args)``  ``{``    ``TreeNode root = ``new` `TreeNode(``5``);``    ``root.left = ``new` `TreeNode(``6``);``    ``root.right = ``new` `TreeNode(``5``);``    ``root.left.right = ``new` `TreeNode(``6``);``    ``root.right.right = ``new` `TreeNode(``5``);` `    ``System.out.println(sameDiag(root));``  ``}``}``// This code is contributed by offbeat`

## Python3

 `# Python3 program of the above approach` `# Structure of a Node``class` `TreeNode:``    ``def` `__init__(``self``, val ``=` `0``, left ``=` `None``, right ``=` `None``):``        ``self``.val ``=` `val``        ``self``.left ``=` `left``        ``self``.right ``=` `right`  `# Function to count diagonal``# paths having same-valued nodes``def` `sameDiag(root):` `    ``# Maps the values of all``    ``# nodes with its diagonal``    ``diag ``=` `{}` `    ``# Stores indexing of diagonal``    ``left ``=` `0` `    ``# Function to perform diagonal``    ``# traversal on the given binary tree``    ``def` `fillMap(root, left):` `        ``# If tree is empty``        ``if` `not` `root:``            ``return` `        ``# If current diagonal is not visited``        ``if` `left ``not` `in` `diag:` `            ``# Update diag[left]``            ``diag[left] ``=` `set``([root.val])` `        ``# Otherwise, map current node``        ``# with its diagonal``        ``else``:``            ``diag[left].add(root.val)` `        ``# Recursively, traverse left subtree``        ``fillMap(root.left, left ``+` `1``)` `        ``# Recursively, traverse right subtree``        ``fillMap(root.right, left)` `    ``# Function call to perform``    ``# diagonal traversal``    ``fillMap(root, left)` `    ``# Stores count of diagonals such``    ``# that all the nodes on the same``    ``# diagonal are equal``    ``count ``=` `0` `    ``# Traverse each diagonal``    ``for` `d ``in` `diag:` `        ``# If all nodes on the current``        ``# diagonal are equal``        ``if` `len``(``list``(diag[d])) ``=``=` `1``:` `            ``# Update count``            ``count ``+``=` `1``    ``return` `count`  `# Driver Code``if` `__name__ ``=``=` `'__main__'``:``    ` `    ` `    ``# Given tree``    ``root ``=` `TreeNode(``5``)``    ``root.left ``=` `TreeNode(``6``)``    ``root.right ``=` `TreeNode(``5``)``    ``root.left.right ``=` `TreeNode(``6``)``    ``root.right.right ``=` `TreeNode(``5``)` `    ``# Function call``    ``print``(sameDiag(root))`
Output:
`2`

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.

My Personal Notes arrow_drop_up