Skip to content
geeksforgeeks
  • Courses
    • DSA to Development
    • Get IBM Certification
    • Newly Launched!
      • Master Django Framework
      • Become AWS Certified
    • For Working Professionals
      • Interview 101: DSA & System Design
      • Data Science Training Program
      • JAVA Backend Development (Live)
      • DevOps Engineering (LIVE)
      • Data Structures & Algorithms in Python
    • For Students
      • Placement Preparation Course
      • Data Science (Live)
      • Data Structure & Algorithm-Self Paced (C++/JAVA)
      • Master Competitive Programming (Live)
      • Full Stack Development with React & Node JS (Live)
    • Full Stack Development
    • Data Science Program
    • All Courses
  • Tutorials
    • Data Structures & Algorithms
    • ML & Data Science
    • Interview Corner
    • Programming Languages
    • Web Development
    • CS Subjects
    • DevOps And Linux
    • School Learning
  • Practice
    • Build your AI Agent
    • GfG 160
    • Problem of the Day
    • Practice Coding Problems
    • GfG SDE Sheet
  • Contests
    • Accenture Hackathon (Ending Soon!)
    • GfG Weekly [Rated Contest]
    • Job-A-Thon Hiring Challenge
    • All Contests and Events
  • DSA
  • Interview Problems on Tree
  • Practice Tree
  • MCQs on Tree
  • Tutorial on Tree
  • Types of Trees
  • Basic operations
  • Tree Traversal
  • Binary Tree
  • Complete Binary Tree
  • Ternary Tree
  • Binary Search Tree
  • Red-Black Tree
  • AVL Tree
  • Full Binary Tree
  • B-Tree
  • Advantages & Disadvantages
Open In App
Next Article:
Count of root to leaf paths in a Binary Tree that form an AP
Next article icon

Maximize count of set bits in a root to leaf path in a binary tree

Last Updated : 17 Aug, 2021
Comments
Improve
Suggest changes
Like Article
Like
Report

Given a binary tree, the task is to find the total count of set bits in the node values of all the root to leaf paths and print the maximum among them.

Examples:

Input:

Output: 12
Explanation:
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.

Input:

Output: 13
Explanation:
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.

 


Approach: 
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:

C++
// C++ Program to implement  // the above approach  #include <bits/stdc++.h>  using namespace std;  int maxm = 0;   // Node structure  struct Node {      int val;       // Pointers to left      // and right child      Node *left, *right;       // Initialize constructor      Node(int x)      {          val = x;          left = NULL;          right = NULL;      }  };   // Function to find the maximum  // count of setbits in a root to leaf  void maxm_setbits(Node* root, int ans)  {      // Check if root is not null      if (!root)          return;       if (root->left == NULL          && root->right == NULL) {           ans += __builtin_popcount(root->val);           // Update the maximum count          // of setbits          maxm = max(ans, maxm);           return;      }       // Traverse left of binary tree      maxm_setbits(root->left,                  ans + __builtin_popcount(                          root->val));       // Traverse right of the binary tree      maxm_setbits(root->right,                  ans + __builtin_popcount(                          root->val));  }   // Driver Code  int main()  {      Node* root = new Node(15);      root->left = new Node(3);      root->right = new Node(7);      root->left->left = new Node(5);      root->left->right = new Node(1);      root->right->left = new Node(31);      root->right->right = new Node(9);       maxm_setbits(root, 0);       cout << maxm << endl;       return 0;  }  
Java
// Java Program to implement  // the above approach  import java.util.*; class GFG{     static int maxm = 0;   // Node structure  static class Node  {      int val;       // Pointers to left      // and right child      Node left, right;       // Initialize constructor      Node(int x)      {          val = x;          left = null;          right = null;      }  };   // Function to find the maximum  // count of setbits in a root to leaf  static void maxm_setbits(Node root, int ans)  {      // Check if root is not null      if (root == null)          return;       if (root.left == null &&          root.right == null)      {          ans += Integer.bitCount(root.val);           // Update the maximum count          // of setbits          maxm = Math.max(ans, maxm);           return;      }       // Traverse left of binary tree      maxm_setbits(root.left,                  ans + Integer.bitCount(                          root.val));       // Traverse right of the binary tree      maxm_setbits(root.right,                  ans + Integer.bitCount(                          root.val));  }   // Driver Code  public static void main(String[] args)  {      Node root = new Node(15);      root.left = new Node(3);      root.right = new Node(7);      root.left.left = new Node(5);      root.left.right = new Node(1);      root.right.left = new Node(31);      root.right.right = new Node(9);       maxm_setbits(root, 0);       System.out.print(maxm +"\n");   }  }   // This code is contributed by Amit Katiyar  
Python3
# Python3 program to implement  # the above approach maxm = 0  # Node class class Node:          # Initialise constructor     def __init__(self, x):                  self.val = x         self.left = None         self.right = None          # Function to count the number of 1 in number def count_1(n):          count = 0     while (n):          count += n & 1         n >>= 1              return count   # Function to find the maximum  # count of setbits in a root to leaf def maxm_setbits(root, ans):          global maxm          # Check if root is null     if not root:         return          if (root.left == None and          root.right == None):         ans += count_1(root.val)                  # Update the maximum count          # of setbits          maxm = max(ans, maxm)         return          # Traverse left of binary tree     maxm_setbits(root.left,                   ans + count_1(root.val))          # Traverse right of the binary tree      maxm_setbits(root.right,                   ans + count_1(root.val))      # Driver code root = Node(15) root.left = Node(3) root.right = Node(7) root.left.left = Node(5) root.left.right = Node(1) root.right.left = Node(31) root.right.right = Node(9)  maxm_setbits(root, 0)  print(maxm)          # This code is contributed by Stuti Pathak 
C#
// C# program for the above approach  using System; class GFG{      // Function to Sort a Bitonic array  // in constant space  static void sortArr(int []a, int n)  {      int i, k;       // Initialise the value of k      k = (int)(Math.Log(n) / Math.Log(2));      k = (int) Math.Pow(2, k);       // In each iteration compare elements      // k distance apart and swap if      // they are not in order      while (k > 0)      {          for(i = 0; i + k < n; i++)              if (a[i] > a[i + k])             {                 int tmp = a[i];                 a[i] = a[i + k];                 a[i + k] = tmp;             }          // k is reduced to half          // after every iteration          k = k / 2;      }       // Print the array elements      for(i = 0; i < n; i++)     {          Console.Write(a[i] + " ");      }  }      // Driver code public static void Main(String[] args)  {          // Given array []arr      int []arr = { 5, 20, 30, 40, 36,                    33, 25, 15, 10 };      int n = arr.Length;           // Function call      sortArr(arr, n);  } }  // This code is contributed by gauravrajput1  
JavaScript
<script>  // JavaScript Program to implement  // the above approach  let maxm = 0;  // Node structure class Node  {          // Initialize constructor     constructor(x)     {         this.val = x;         this.left = null;         this.right = null;     } }  var root;  // Function to find the maximum  // count of setbits in a root to leaf  function maxm_setbits(root, ans)  {           // Check if root is not null      if (!root)          return;       if (root.left == null &&         root.right == null)      {           ans += (root.val).toString(2).split('').filter(           y => y == '1').length;          // Update the maximum count          // of setbits          maxm = Math.max(ans, maxm);           return;      }       // Traverse left of binary tree      maxm_setbits(root.left,     ans + (root.val).toString(2).split('').filter(      y => y == '1').length);       // Traverse right of the binary tree      maxm_setbits(root.right,      ans + (root.val).toString(2).split('').filter(       y => y == '1').length);  }   // Driver Code root = new Node(15);  root.left = new Node(3);  root.right = new Node(7);  root.left.left = new Node(5);  root.left.right = new Node(1);  root.right.left = new Node(31);  root.right.right = new Node(9);   maxm_setbits(root, 0);   document.write(maxm);  // This code is contributed by Dharanendra L V.  </script> 

Output: 
12

 

Time Complexity: O(N), where N denotes the number of nodes. 
Auxiliary Space: O(1)
 


Next Article
Count of root to leaf paths in a Binary Tree that form an AP
author
mohit kumar 29
Improve
Article Tags :
  • Bit Magic
  • Tree
  • Searching
  • Recursion
  • DSA
  • setBitCount
  • Tree Traversals
Practice Tags :
  • Bit Magic
  • Recursion
  • Searching
  • Tree

Similar Reads

  • Find the maximum sum leaf to root path in a Binary Tree
    Given a Binary Tree, the task is to find the maximum sum path from a leaf to a root. Example : Input: Output: 60Explanantion: There are three leaf to root paths 20->30->10, 5->30->10 and 15->10. The sums of these three paths are 60, 45 and 25 respectively. The maximum of them is 60 an
    15+ min read
  • Count of root to leaf paths in a Binary Tree that form an AP
    Given a Binary Tree, the task is to count all paths from root to leaf which forms an Arithmetic Progression. Examples: Input: Output: 2 Explanation: The paths that form an AP in the given tree from root to leaf are: 1->3->5 (A.P. with common difference 2)1->6->11 (A.P. with common differ
    7 min read
  • Maximize sum of path from the Root to a Leaf node in N-ary Tree
    Given a generic tree consisting of n nodes, the task is to find the maximum sum of the path from the root to the leaf node. Examples: Input: Output: 12Explanation: The path sum to every leaf from the root are:For node 4: 1 -> 2 -> 4 = 7For node 5: 1 -> 2 -> 5 = 8For node 6: 1 -> 3 -
    5 min read
  • Maximum value of Bitwise AND from root to leaf in a Binary tree
    Given a Binary Tree, the task is to find the maximum value of Bitwise AND from any path from the root node to the leaf node. Examples: Input: Below is the given graph: Output: 7Explanation:path 1: 15->3->5 = (15 & 3 & 5) = 1path 2: 15->3->1 =(15 & 3 & 1) = 1path 3: 15-
    7 min read
  • Find all root to leaf path sum of a Binary Tree
    Given a Binary Tree, the task is to print all the root to leaf path sum of the given Binary Tree. Examples: Input: 30 / \ 10 50 / \ / \ 3 16 40 60 Output: 43 56 120 140 Explanation: In the above binary tree there are 4 leaf nodes. Hence, total 4 path sum are present from root node to the leaf node.
    8 min read
  • Count of 1's in any path in a Binary Tree
    Given a binary tree of 0s and 1s, the task is to find the maximum number of 1s in any path in the tree. The path may start and end at any node in the tree.Example: Input: 1 / \ 0 1 / \ 1 1 / \ 1 0 Output: 4 Approach: A function countUntil has been created which returns the maximum count of 1 in any
    10 min read
  • Print the number of set bits in each node of a Binary Tree
    Given a Binary Tree. The task is to print the number of set bits in each of the nodes in the Binary Tree. The idea is to traverse the given binary tree using any tree traversal method, and for each node calculate the number of set bits and print it. Note: One can also use the __builtin_popcount() fu
    6 min read
  • Root to leaf paths having equal lengths in a Binary Tree
    Given a binary tree, print the number of root to leaf paths having equal lengths. Examples: Input : Root of below tree 10 / \ 8 2 / \ / \ 3 5 2 4 Output : 4 paths are of length 3. Input : Root of below tree 10 / \ 8 2 / \ / \ 3 5 2 4 / \ 9 1 Output : 2 paths are of length 3 2 paths are of length 4Re
    8 min read
  • Print the first shortest root to leaf path in a Binary Tree
    Given a Binary Tree with distinct values, the task is to find the first smallest root to leaf path. We basically need to find the leftmost root to leaf path that has the minimum number of nodes. The root to leaf path in below image is 1-> 3 which is the leftmost root to leaf path that has the min
    8 min read
  • Boundary Root to Leaf Path traversal of a Binary Tree
    Given a Binary Tree, the task is to print all Root to Leaf path of this tree in Boundary Root to Leaf path traversal. Boundary Root to Leaf Path Traversal: In this traversal, the first Root to Leaf path(Left boundary) is printed first, followed by the last Root to Leaf path (Right boundary) in Rever
    15+ min read
geeksforgeeks-footer-logo
Corporate & Communications Address:
A-143, 7th Floor, Sovereign Corporate Tower, Sector- 136, Noida, Uttar Pradesh (201305)
Registered Address:
K 061, Tower K, Gulshan Vivante Apartment, Sector 137, Noida, Gautam Buddh Nagar, Uttar Pradesh, 201305
GFG App on Play Store GFG App on App Store
Advertise with us
  • Company
  • About Us
  • Legal
  • Privacy Policy
  • In Media
  • Contact Us
  • Advertise with us
  • GFG Corporate Solution
  • Placement Training Program
  • Languages
  • Python
  • Java
  • C++
  • PHP
  • GoLang
  • SQL
  • R Language
  • Android Tutorial
  • Tutorials Archive
  • DSA
  • Data Structures
  • Algorithms
  • DSA for Beginners
  • Basic DSA Problems
  • DSA Roadmap
  • Top 100 DSA Interview Problems
  • DSA Roadmap by Sandeep Jain
  • All Cheat Sheets
  • Data Science & ML
  • Data Science With Python
  • Data Science For Beginner
  • Machine Learning
  • ML Maths
  • Data Visualisation
  • Pandas
  • NumPy
  • NLP
  • Deep Learning
  • Web Technologies
  • HTML
  • CSS
  • JavaScript
  • TypeScript
  • ReactJS
  • NextJS
  • Bootstrap
  • Web Design
  • Python Tutorial
  • Python Programming Examples
  • Python Projects
  • Python Tkinter
  • Python Web Scraping
  • OpenCV Tutorial
  • Python Interview Question
  • Django
  • Computer Science
  • Operating Systems
  • Computer Network
  • Database Management System
  • Software Engineering
  • Digital Logic Design
  • Engineering Maths
  • Software Development
  • Software Testing
  • DevOps
  • Git
  • Linux
  • AWS
  • Docker
  • Kubernetes
  • Azure
  • GCP
  • DevOps Roadmap
  • System Design
  • High Level Design
  • Low Level Design
  • UML Diagrams
  • Interview Guide
  • Design Patterns
  • OOAD
  • System Design Bootcamp
  • Interview Questions
  • Inteview Preparation
  • Competitive Programming
  • Top DS or Algo for CP
  • Company-Wise Recruitment Process
  • Company-Wise Preparation
  • Aptitude Preparation
  • Puzzles
  • School Subjects
  • Mathematics
  • Physics
  • Chemistry
  • Biology
  • Social Science
  • English Grammar
  • Commerce
  • World GK
  • GeeksforGeeks Videos
  • DSA
  • Python
  • Java
  • C++
  • Web Development
  • Data Science
  • CS Subjects
@GeeksforGeeks, Sanchhaya Education Private Limited, All rights reserved
We use cookies to ensure you have the best browsing experience on our website. By using our site, you acknowledge that you have read and understood our Cookie Policy & Privacy Policy
Lightbox
Improvement
Suggest Changes
Help us improve. Share your suggestions to enhance the article. Contribute your expertise and make a difference in the GeeksforGeeks portal.
geeksforgeeks-suggest-icon
Create Improvement
Enhance the article with your expertise. Contribute to the GeeksforGeeks community and help create better learning resources for all.
geeksforgeeks-improvement-icon
Suggest Changes
min 4 words, max Words Limit:1000

Thank You!

Your suggestions are valuable to us.

What kind of Experience do you want to share?

Interview Experiences
Admission Experiences
Career Journeys
Work Experiences
Campus Experiences
Competitive Exam Experiences