Given a Binary Tree, find count of distinct nodes in a root to leaf path with maximum distinct nodes.
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
Time Complexity :O(n)
This article is contributed by Nishant Singh. If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to email@example.com. 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.
Don’t stop now and take your learning to the next level. Learn all the important concepts of Data Structures and Algorithms with the help of the most trusted course: DSA Self Paced. Become industry ready at a student-friendly price.
- Sum of nodes on the longest path from root to leaf node
- Find the maximum sum leaf to root path in a Binary Tree
- Find if there is a pair in root to a leaf path with sum equals to root's data
- Implementing a BST where every node stores the maximum number of nodes in the path till any leaf
- GCD from root to leaf path in an N-ary tree
- Root to leaf path sum equal to a given number
- Check if there is a root to leaf path with given sequence
- Shortest root to leaf path sum equal to a given number
- Root to leaf path product equal to a given number
- Print the first shortest root to leaf path in a Binary Tree
- Boundary Root to Leaf Path traversal of a Binary Tree
- Remove nodes on root to leaf paths of length < K
- Print the path common to the two paths from the root to the two given nodes
- Find the path from root to the given nodes of a tree for multiple queries
- Print path from root to all nodes in a Complete Binary Tree
- Maximum XOR with given value in the path from root to given node in the tree
- Maximum sum of leaf nodes among all levels of the given binary tree
- Maximum sum of non-leaf nodes among all levels of the given binary tree
- Maximum number of leaf nodes that can be visited within the given budget
- Print common nodes on path from root (or common ancestors)
If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to firstname.lastname@example.org. See your article appearing on the GeeksforGeeks main page and help other Geeks.
Please Improve this article if you find anything incorrect by clicking on the "Improve Article" button below.