• Tutorials
  • DSA
  • Data Science
  • Web Tech
  • Courses
June 01, 2022 |1.4K Views

Root to leaf path with maximum distinct nodes

  Share   Like
Description
Discussion

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.

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.

Root to leaf path with maximum distinct nodes: https://www.geeksforgeeks.org/maximum-distinct-nodes-in-a-root-to-leaf-path/