Open In App

Maximum distinct nodes in a Root to leaf path

Last Updated : 18 Sep, 2023
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)



Similar Reads

Construct a Tree whose sum of nodes of all the root to leaf path is not divisible by the count of nodes in that path
Given an N-ary tree consisting of N nodes numbered from 1 to N rooted at node 1, the task is to assign values to each node of the tree such that the sum of values from any root to the leaf path which contains at least two nodes is not divisible by the number of nodes along that path. Examples: Input: N = 11, edges[][] = {{1, 2}, {1, 3}, {1, 4}, {1,
11 min read
Find if there is a pair in root to a leaf path with sum equals to root's data
Given a binary tree, find if there is a pair in root to a leaf path such that sum of values in pair is equal to root's data. For example, in below tree there are no pairs in any root to leaf path with sum equal to root's data. The idea is based on hashing and tree traversal. The idea is similar to method 2 of array pair sum problem. Create an empty
8 min read
Sum of nodes on the longest path from root to leaf node
Given a binary tree containing n nodes. The problem is to find the sum of all nodes on the longest path from root to leaf node. If two or more paths compete for the longest path, then the path having maximum sum of nodes is being considered. Examples: Input : Binary tree: 4 / \ 2 5 / \ / \ 7 1 2 3 / 6 Output : 13 4 / \ 2 5 / \ / \ 7 1 2 3 / 6 The h
19 min read
Count root to leaf paths having exactly K distinct nodes in a Binary Tree
Given a Binary Tree consisting of N nodes rooted at 1, an integer K and an array arr[] consisting of values assigned to each node, the task is to count the number of root to leaf paths having exactly K distinct nodes in the given Binary Tree. Examples: Input: N = 3, Edges[][] = {{1, 2}, {1, 3}}, arr[] = {3, 3, 2}, K = 2, Below is the given Tree: Ou
11 min read
Find the maximum sum leaf to root path in a Binary Tree
Given a Binary Tree, find the maximum sum path from a leaf to root. For example, in the following tree, there are three leaf to root paths 8-&gt;-2-&gt;10, -4-&gt;-2-&gt;10 and 7-&gt;10. The sums of these three paths are 16, 4 and 17 respectively. The maximum of them is 17 and the path for maximum is 7-&gt;10. 10 / \ -2 7 / \ 8 -4 Recommended Pract
14 min read
Maximum coins such that root to leaf path sum is positive
Given tree with N vertices rooted at node 0, edges given by array edges[][] and array arr[] of size N representing coins[] on each node. In one operation pick any node and collect all its coins. Task for this problem is to find maximum number of coins collected such that path sum from root node to any leaf node remains positive (path sum from root
10 min read
Print all root-to-leaf paths with maximum count of even nodes
Given a Binary tree, the task is to print all possible root-to-leaf paths having a maximum number of even valued nodes. Examples: Input: 2 / \ 6 3 / \ \ 4 7 11 / \ \ 10 12 1 Output: 2 -&gt; 6 -&gt; 4 -&gt; 10 2 -&gt; 6 -&gt; 4 -&gt; 12 Explanation: Count of even nodes on the path 2 -&gt; 6 -&gt; 4 -&gt; 10 = 4 Count of even nodes on the path 2 -
13 min read
Print the longest leaf to leaf path in a Binary tree
C/C++ Code // C++ program to print the longest leaf to leaf // path #include &lt;bits/stdc++.h&gt; using namespace std; // Tree node structure used in the program struct Node { int data; Node *left, *right; }; struct Node* newNode(int data) { struct Node* node = new Node; node-&gt;data = data; node-&gt;left = node-&gt;right = NULL; return (node); }
28 min read
Sum of Bitwise AND of the sum of all leaf and non-leaf nodes for each level of a Binary Tree
Given a Binary Tree consisting of N nodes, the task is to find the sum of Bitwise AND of the sum of all leaf nodes and the sum of all non-leaf nodes for each level in the given Tree. Examples: Input: Below is the given tree: 5 / \ 3 9 / \ 6 4 \ 7Output: 5Explanation: For Level 1: leaf node sum = 0, non-leaf node sum = 5. So, 0&amp;5 = 0. For Level
10 min read
Implementing a BST where every node stores the maximum number of nodes in the path till any leaf
Given an array of values. The task is to implement a Binary Search Tree using values of the array where every node stores the maximum number of nodes in the path starting from the node itself and ending at any leaf of the tree. Note: The maximum number of nodes in the path from any node to any leaf node in a BST is the height of the subtree rooted
15 min read
Article Tags :
Practice Tags :