Path 1: 15(1111)->3(0011)->5(0101) = 8
Path 2: 15(1111)->3(0011)->1(0001) = 7
Path 3: 15(01111)->7(00111)->31(11111) = 12 (maximum)
Path 4: 15(1111)->7(0111)->9(1001) = 9
Therefore, the maximum count of set bits obtained in a path is 12.
Path 1: 31(11111)->3(00011)->7(00111) = 10
Path 2: 31(11111)->3(00011)->1(00001) = 8
Path 3: 31(11111)->15(01111)->5(00101) = 11
Path 4: 31(11111)->15(01111)->23(10111) = 13 (maximum)
Therefore, the maximum count of set bits obtained in a path is 13.
Follow the steps below to solve the problem:
- Traverse each node recursively, starting from the root node
- Calculate the number of set bits in the value of the current node.
- Update the maximum count of set bits(stored in a variable, say maxm).
- Traverse its left and right subtree.
- After complete traversal of all the nodes of the tree, print the final value of maxm as the answer.
Below is the implementation of the above approach:
Time Complexity: O(N), where N denotes the number of nodes.
Auxiliary Space: O(1)
Attention reader! Don’t stop learning now. Get hold of all the important DSA concepts with the DSA Self Paced Course at a student-friendly price and become industry ready.
- Find if there is a pair in root to a leaf path with sum equals to root's data
- Print the longest leaf to leaf path in a Binary tree
- Find the maximum sum leaf to root path in a Binary Tree
- Boundary Root to Leaf Path traversal of a Binary Tree
- Print the longest path from root to leaf in a Binary tree
- Find all root to leaf path sum of a Binary Tree
- Print the first shortest root to leaf path in a Binary Tree
- GCD from root to leaf path in an N-ary tree
- Count of root to leaf paths in a Binary Tree that form an AP
- Count the number of paths from root to leaf of a Binary tree with given XOR value
- Count of root to leaf paths whose permutation is palindrome in a Binary Tree
- Count root to leaf paths having exactly K distinct nodes in a Binary Tree
- Given a binary tree, print out all of its root-to-leaf paths one per line.
- Given a binary tree, print all root-to-leaf paths
- Root to leaf paths having equal lengths in a Binary Tree
- Maximum value of Bitwise AND from root to leaf in a Binary tree
- Find maximum GCD value from root to leaf in a Binary tree
- Remove nodes from Binary Tree such that sum of all remaining root-to-leaf paths is atleast K
- Root to leaf path sum equal to a given number
- Check if there is a root to leaf path with given sequence
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 Improve this article if you find anything incorrect by clicking on the "Improve Article" button below.