Open In App

Maximum distinct nodes in a Root to leaf path

Improve
Improve
Like Article
Like
Save
Share
Report

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.

Algorithm:

  1. Create a function largestUniquePathUtil(node, hash) that takes a node of a binary tree and a hash that stores all node values as arguments.
  2. If the node is NULL, return the size of the hash.
  3. Put the node value into the hash.
  4. Recursively call the function on the left and right children of the node and store the returned value in the variable max_path.
  5. Remove the current node value from the hash.
  6. If all duplicate values of the current node are deleted from the hash, erase the key from the hash.
  7. Return the max_path variable.
  8. Create a function largestUniquePath(node) that takes a node of a binary tree as an argument.
  9. Create an empty hash.
  10. Return the value returned by the function largestUniquePathUtil(node, hash).
  11. In the main function:
  12. Create the binary tree.
  13. Call the function largestUniquePath() and print the result.

Below is implementation of above idea 

C++




// 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 tree
struct Node {
    int data;
    struct Node *left, *right;
};
  
// A utility function to create a new Binary
// Tree node
Node* newNode(int data)
{
    Node* temp = new Node;
    temp->data = data;
    temp->left = temp->right = NULL;
    return temp;
}
  
int largestUniquePathUtil(Node* node, unordered_map<int, int> m)
{
    if (!node)
        return m.size();
  
    // put this node into hash
    m[node->data]++;
  
    int max_path = max(largestUniquePathUtil(node->left, m),
                       largestUniquePathUtil(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 path
int largestUniquePath(Node* node)
{
    if (!node)
        return 0;
  
    // hash that store all node value
    unordered_map<int, int> hash;
  
    // return max length unique value path
    return largestUniquePathUtil(node, hash);
}
  
// Driver program to test above functions
int 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 << largestUniquePath(root) << endl;
  
    return 0;
}


Java




// Java program to find count of distinct nodes
// on a path with maximum distinct nodes.
import java.util.*;
class GFG 
  
// A node of binary tree
static class Node 
{
    int data;
    Node left, right;
};
  
// A utility function to create a new Binary
// Tree node
static Node newNode(int data)
{
    Node temp = new Node();
    temp.data = data;
    temp.left = temp.right = null;
    return temp;
}
  
static int largestUniquePathUtil(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(largestUniquePathUtil(node.left, m),
                            largestUniquePathUtil(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 path
static int largestUniquePath(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 largestUniquePathUtil(node, hash);
}
  
// Driver Code
public 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(largestUniquePath(root));    
}
}
  
// This code is contributed by Princi Singh


Python3





C#





Javascript





Output

4

Time Complexity: O(n) 

Auxiliary Space: O(n)



Last Updated : 18 Sep, 2023
Like Article
Save Article
Previous
Next
Share your thoughts in the comments
Similar Reads