Maximum distinct nodes in a Root to leaf path - GeeksforGeeks

10 Mar, 2022
Given a Binary Tree, find count of distinct nodes in all the root to leaf paths and print the maximum. Examples:  
Input :   1
        /    \
       2      3
      / \    / \
     4   5  6   3
             \   \
              8   9 
Output : 4 
The root to leaf path with maximum distinct
nodes is 1-3-6-8.
 
A simple solution is to explore all root to leaf paths. In every root to leaf path, count distinct nodes and finally return the maximum count.An efficient solution is to use hashing. We recursively traverse the tree and maintain count of distinct nodes on path from root to current node. We recur for left and right subtrees and finally return maximum of two values.Below is implementation of above idea  
C++
Java
Python3
C#
Javascript
// C++ program to find count of distinct nodes// on a path with maximum distinct nodes.#include <bits/stdc++.h>using namespace std; // A node of binary treestruct Node {    int data;    struct Node *left, *right;}; // A utility function to create a new Binary// Tree nodeNode* newNode(int data){    Node* temp = new Node;    temp->data = data;    temp->left = temp->right = NULL;    return temp;} int largestUinquePathUtil(Node* node, unordered_map<int, int> m){    if (!node)        return m.size();     // put this node into hash    m[node->data]++;     int max_path = max(largestUinquePathUtil(node->left, m),                       largestUinquePathUtil(node->right, m));     // remove current node from path "hash"    m[node->data]--;     // if we reached a condition where all duplicate value    // of current node is deleted    if (m[node->data] == 0)        m.erase(node->data);     return max_path;} // A utility function to find long unique value pathint largestUinquePath(Node* node){    if (!node)        return 0;     // hash that store all node value    unordered_map<int, int> hash;     // return max length unique value path    return largestUinquePathUtil(node, hash);} // Driver program to test above functionsint main(){    // Create binary tree shown in above figure    Node* root = newNode(1);    root->left = newNode(2);    root->right = newNode(3);    root->left->left = newNode(4);    root->left->right = newNode(5);    root->right->left = newNode(6);    root->right->right = newNode(7);    root->right->left->right = newNode(8);    root->right->right->right = newNode(9);     cout << largestUinquePath(root) << endl;     return 0;}
// Java program to find count of distinct nodes// on a path with maximum distinct nodes.import java.util.*;class GFG{ // A node of binary treestatic class Node{    int data;    Node left, right;}; // A utility function to create a new Binary// Tree nodestatic Node newNode(int data){    Node temp = new Node();    temp.data = data;    temp.left = temp.right = null;    return temp;} static int largestUinquePathUtil(Node node, HashMap<Integer,                                                    Integer> m){    if (node == null)        return m.size();     // put this node into hash    if(m.containsKey(node.data))    {        m.put(node.data, m.get(node.data) + 1);    }    else    {        m.put(node.data, 1);    }     int max_path = Math.max(largestUinquePathUtil(node.left, m),                            largestUinquePathUtil(node.right, m));     // remove current node from path "hash"    if(m.containsKey(node.data))    {        m.put(node.data, m.get(node.data) - 1);    }     // if we reached a condition where all duplicate value    // of current node is deleted    if (m.get(node.data) == 0)        m.remove(node.data);     return max_path;} // A utility function to find long unique value pathstatic int largestUinquePath(Node node){    if (node == null)        return 0;     // hash that store all node value    HashMap<Integer,            Integer> hash = new HashMap<Integer,                                        Integer>();     // return max length unique value path    return largestUinquePathUtil(node, hash);} // Driver Codepublic static void main(String[] args){    // Create binary tree shown in above figure    Node root = newNode(1);    root.left = newNode(2);    root.right = newNode(3);    root.left.left = newNode(4);    root.left.right = newNode(5);    root.right.left = newNode(6);    root.right.right = newNode(7);    root.right.left.right = newNode(8);    root.right.right.right = newNode(9);     System.out.println(largestUinquePath(root));   }} // This code is contributed by Princi Singh
# Python3 program to find count of# distinct nodes on a path with# maximum distinct nodes. # A utility class to create a# new Binary Tree nodeclass newNode:    def __init__(self, data):        self.data = data        self.left = self.right = None def largestUinquePathUtil(node, m):    if (not node or node.data in m):        return len(m)     # put this node into hash    if node.data in m:        m[node.data] += 1    else:        m[node.data] = 1     max_path = max(largestUinquePathUtil(node.left, m),                   largestUinquePathUtil(node.right, m))     # remove current node from path "hash"    m[node.data] -= 1     # if we reached a condition    # where all duplicate value    # of current node is deleted    if (m[node.data] == 0):        del m[node.data]     return max_path # A utility function to find# long unique value pathdef largestUinquePath(node):    if (not node):        return 0     # hash that store all node value    Hash = {}     # return max length unique value path    return largestUinquePathUtil(node, Hash) # Driver Codeif __name__ == '__main__':     # Create binary tree shown    # in above figure    root = newNode(1)    root.left = newNode(2)    root.right = newNode(3)    root.left.left = newNode(4)    root.left.right = newNode(5)    root.right.left = newNode(6)    root.right.right = newNode(7)    root.right.left.right = newNode(8)    root.right.right.right = newNode(9)     print(largestUinquePath(root)) # This code is contributed by PranchalK
// C# program to find count of distinct nodes// on a path with maximum distinct nodes.using System;using System.Collections.Generic; class GFG{ // A node of binary treepublic class Node{    public int data;    public Node left, right;}; // A utility function to create a new Binary// Tree nodestatic Node newNode(int data){    Node temp = new Node();    temp.data = data;    temp.left = temp.right = null;    return temp;} static int largestUinquePathUtil(Node node,                                 Dictionary<int, int> m){    if (node == null)        return m.Count;     // put this node into hash    if(m.ContainsKey(node.data))    {        m[node.data] = m[node.data] + 1;    }    else    {        m.Add(node.data, 1);    }     int max_path = Math.Max(largestUinquePathUtil(node.left, m),                            largestUinquePathUtil(node.right, m));     // remove current node from path "hash"    if(m.ContainsKey(node.data))    {        m[node.data] = m[node.data] - 1;    }     // if we reached a condition where all    // duplicate value of current node is deleted    if (m[node.data] == 0)        m.Remove(node.data);     return max_path;} // A utility function to find long unique value pathstatic int largestUinquePath(Node node){    if (node == null)        return 0;     // hash that store all node value    Dictionary<int,                   int> hash = new Dictionary<int,                                          int>();     // return max length unique value path    return largestUinquePathUtil(node, hash);} // Driver Codepublic static void Main(String[] args){         // Create binary tree shown in above figure    Node root = newNode(1);    root.left = newNode(2);    root.right = newNode(3);    root.left.left = newNode(4);    root.left.right = newNode(5);    root.right.left = newNode(6);    root.right.right = newNode(7);    root.right.left.right = newNode(8);    root.right.right.right = newNode(9);     Console.WriteLine(largestUinquePath(root));}} // This code is contributed by 29AjayKumar
<script>     // JavaScript program to find count of distinct nodes    // on a path with maximum distinct nodes.         class Node    {        constructor(data) {           this.left = null;           this.right = null;           this.data = data;        }    }         // A utility function to create a new Binary    // Tree node    function newNode(data)    {        let temp = new Node(data);        return temp;    }     function largestUinquePathUtil(node, m)    {        if (node == null)            return m.size;         // put this node into hash        if(m.has(node.data))        {            m.set(node.data, m.get(node.data) + 1);        }        else        {            m.set(node.data, 1);        }         let max_path = Math.max(largestUinquePathUtil(node.left, m),                                largestUinquePathUtil(node.right, m));         // remove current node from path "hash"        if(m.has(node.data))        {            m.set(node.data, m.get(node.data) - 1);        }         // if we reached a condition where all duplicate value        // of current node is deleted        if (m.get(node.data) == 0)            m.delete(node.data);         return max_path;    }     // A utility function to find long unique value path    function largestUinquePath(node)    {        if (node == null)            return 0;         // hash that store all node value        let hash = new Map();         // return max length unique value path        return largestUinquePathUtil(node, hash);    }         // Create binary tree shown in above figure    let root = newNode(1);    root.left = newNode(2);    root.right = newNode(3);    root.left.left = newNode(4);    root.left.right = newNode(5);    root.right.left = newNode(6);    root.right.right = newNode(7);    root.right.left.right = newNode(8);    root.right.right.right = newNode(9);       document.write(largestUinquePath(root));    </script>
Output:
4
Time Complexity :O(n)  
YouTubeGeeksforGeeks507K subscribersRoot to leaf path with maximum distinct nodes | GeeksforGeeksWatch laterShareCopy linkInfoShoppingTap to unmuteIf playback doesn't begin shortly, try restarting your device.You're signed outVideos you watch may be added to the TV's watch history and influence TV recommendations. To avoid this, cancel and sign in to YouTube on your computer.CancelConfirmMore videosMore videosSwitch cameraShareInclude playlistAn error occurred while retrieving sharing information. Please try again later.Watch on0:000:000:00 / 6:25•Live•<div class="player-unavailable"><h1 class="message">An error occurred.</h1><div class="submessage"><a href="https://www.youtube.com/watch?v=YYvhvJA_sqA" target="_blank">Try watching this video on www.youtube.com</a>, or enable JavaScript if it is disabled in your browser.</div></div>
?list=PLqM7alHXFySHCXD7r1J0ky9Zg_GBB1dbk 
This article is contributed by Nishant Singh. If you like GeeksforGeeks and would like to contribute, you can also write an article using write.geeksforgeeks.org or mail your article to review-team@geeksforgeeks.org. See your article appearing on the GeeksforGeeks main page and help other Geeks.Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above. 
 
PranchalKatiyar
princi singh
29AjayKumar
rameshtravel07
adarsh_007
cpp-unordered_map
Hash
Tree
Hash
Tree
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Hashing | Set 2 (Separate Chaining)
Sort string of characters
Counting frequencies of array elements
Most frequent element in an array
Sorting a Map by value in C++ STL
Tree Traversals (Inorder, Preorder and Postorder)
Binary Tree | Set 1 (Introduction)
AVL Tree | Set 1 (Insertion)
Level Order Binary Tree Traversal
Binary Tree | Set 3 (Types of Binary Tree)