Javatpoint Logo
Javatpoint Logo

Maximum number of distinct nodes in a root-to-leaf path

Find the maximum number of distinct nodes in all root-to-leaf paths given a Binary Tree.

Examples

Exploring all root to leaf paths is a simple solution. Count distinct nodes along each root-to-leaf path and return the maximum number.

Hashing is an efficient solution. We traverse the tree recursively, keeping track of the number of distinct nodes on the path from the root to the current node. We repeat for the left and right subtrees, returning the maximum of two values.

The implementation of the above idea is shown below.

Program in C++

Output

4

Time Complexity : O (n)







Youtube For Videos Join Our Youtube Channel: Join Now

Feedback


Help Others, Please Share

facebook twitter pinterest

Learn Latest Tutorials


Preparation


Trending Technologies


B.Tech / MCA