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:
Maximum average of subtree values in a given Binary Tree
Next article icon

Maximum number in Binary tree of binary values

Last Updated : 18 Jan, 2024
Comments
Improve
Suggest changes
Like Article
Like
Report

Given a binary tree consisting of nodes, each containing a binary value of either 0 or 1, the task is to find the maximum decimal number that can be formed by traversing from the root to a leaf node. The maximum number is achieved by concatenating the binary values along the path from the root to a leaf.

Examples:

Input:

1
/ \
0 1
/ \ / \
0 1 1 0

Output: 7
Explaination: The possible binary numbers are 100, 101, 111, 110, So the maximum number in decimal is 7 (111).

Input:

1
/ \
1 0
/ \ \
0 1 0
/
1

Output: 15
Explaination: The possible binary numbers are 110, 1111, 100. So the maximum number in decimal is 15 (1111).

Approach: To solve the problem follow the below Intuition:

The algorithm in binary tree is a DFS recursive traversal, accumulating the binary number as it traverses the tree from the root to the leaves. At each node, the binary number is updated by shifting it left (equivalent to multiplying by 2) and adding the binary value of the current node. The algorithm considers both left and right subtrees, comparing their maximum binary numbers. By the end of the traversal, the algorithm returns the maximum binary number that can be formed from the root to any leaf in the binary tree.

Follow the steps to solve the problem:

  • Declare a currentNumber, which is the binary number formed from the root node to the current node.
  • Travese recusively and if the current node is NULL (i.e., a leaf node is reached, thus base case hits), then return 0 because there is no number to add to the currentNumber.
  • The currentNumber is updated by shifting it left (equivalent to multiplying by 2) and adding the binary value of the current node (0 or 1) using bitwise OR operation.
  • The function then recursively calls itself for the left and right children, passing the updated currentNumber. It calculates the maximum binary number for the left and right subtrees.
  • Finally, returns the maximum of the currentNumber and the maximum binary numbers obtained from the left and right subtrees.

Below is the implementation for the above approach:

C++14
// C++ implementation of above approach #include <bits/stdc++.h> using namespace std;  // Bulid tree class class Node { public:     int data;     Node* left;     Node* right;     Node(int val)     {         data = val;         left = NULL;         right = NULL;     } };  int findMaxBinaryNumber(Node* root, int currentNumber) {     if (root == NULL) {         return 0;     }      // Update the currentNumber by shifting     // left and adding the node's value     currentNumber = (currentNumber << 1) | root->data;      // Recursively find the maximum number     // in the left and right subtrees     int leftMax         = findMaxBinaryNumber(root->left, currentNumber);     int rightMax         = findMaxBinaryNumber(root->right, currentNumber);      // Return the maximum of the current subtree     return max(currentNumber, max(leftMax, rightMax)); }  // Driver Code int main() {      // Create a binary tree     Node* root = new Node(1);     root->left = new Node(0);     root->right = new Node(1);     root->left->left = new Node(0);     root->left->right = new Node(1);     root->right->left = new Node(1);     root->right->right = new Node(0);      // Find the maximum binary number in the tree     int maxNumber = findMaxBinaryNumber(root, 0);     cout << "Maximum Binary Number: " << maxNumber;      return 0; } 
Java
// Java implementation of the above approach import java.util.*;  // Build tree class class Node {     int data;     Node left, right;      public Node(int val)     {         data = val;         left = right = null;     } }  public class GFG {     // Function to find the maximum binary number     static int findMaxBinaryNumber(Node root,                                    int currentNumber)     {         if (root == null) {             return 0;         }          // Update the currentNumber by shifting         // left and adding the node's value         currentNumber = (currentNumber << 1) | root.data;          // Recursively find the maximum number         // in the left and right subtrees         int leftMax             = findMaxBinaryNumber(root.left, currentNumber);         int rightMax = findMaxBinaryNumber(root.right,                                            currentNumber);          // Return the maximum of the current subtree         return Math.max(currentNumber,                         Math.max(leftMax, rightMax));     }      // Driver code     public static void main(String[] args)     {         // Create a binary tree         Node root = new Node(1);         root.left = new Node(0);         root.right = new Node(1);         root.left.left = new Node(0);         root.left.right = new Node(1);         root.right.left = new Node(1);         root.right.right = new Node(0);          // Find the maximum binary number in the tree         int maxNumber = findMaxBinaryNumber(root, 0);         System.out.println("Maximum Binary Number: "                            + maxNumber);     } }  // This code is contributed by Susobhan Akhuli 
Python3
class Node:     def __init__(self, val):         self.data = val         self.left = None         self.right = None  def find_max_binary_number(root, current_number):     if not root:         return 0      # Update the current_number by shifting left and adding the node's value     current_number = (current_number << 1) | root.data      # Recursively find the maximum number in the left and right subtrees     left_max = find_max_binary_number(root.left, current_number)     right_max = find_max_binary_number(root.right, current_number)      # Return the maximum of the current subtree     return max(current_number, max(left_max, right_max))  # Driver Code if __name__ == "__main__":     # Create a binary tree     root = Node(1)     root.left = Node(0)     root.right = Node(1)     root.left.left = Node(0)     root.left.right = Node(1)     root.right.left = Node(1)     root.right.right = Node(0)      # Find the maximum binary number in the tree     max_number = find_max_binary_number(root, 0)     print("Maximum Binary Number:", max_number)  # This code is cotributed by akshitaguprzj3 
C#
using System;  // Build tree class class Node {     public int data;     public Node left;     public Node right;      public Node(int val)     {         data = val;         left = null;         right = null;     } }  class GFG {     static int FindMaxBinaryNumber(Node root, int currentNumber)     {         if (root == null)         {             return 0;         }          // Update the currentNumber by shifting         // left and adding the node's value         currentNumber = (currentNumber << 1) | root.data;          // Recursively find the maximum number         // in the left and right subtrees         int leftMax = FindMaxBinaryNumber(root.left, currentNumber);         int rightMax = FindMaxBinaryNumber(root.right, currentNumber);          // Return the maximum of the current subtree         return Math.Max(currentNumber, Math.Max(leftMax, rightMax));     }      // Driver Code     static void Main()     {         // Create a binary tree         Node root = new Node(1);         root.left = new Node(0);         root.right = new Node(1);         root.left.left = new Node(0);         root.left.right = new Node(1);         root.right.left = new Node(1);         root.right.right = new Node(0);          // Find the maximum binary number in the tree         int maxNumber = FindMaxBinaryNumber(root, 0);         Console.WriteLine("Maximum Binary Number: " + maxNumber);     } } 
JavaScript
// JavaScript implementation of above approach  // Build tree class class Node {     constructor(val) {         this.data = val;         this.left = null;         this.right = null;     } }  function findMaxBinaryNumber(root, currentNumber) {     if (root === null) {         return 0;     }      // Update the currentNumber by shifting     // left and adding the node's value     currentNumber = (currentNumber << 1) | root.data;      // Recursively find the maximum number     // in the left and right subtrees     let leftMax = findMaxBinaryNumber(root.left, currentNumber);     let rightMax = findMaxBinaryNumber(root.right, currentNumber);      // Return the maximum of the current subtree     return Math.max(currentNumber, Math.max(leftMax, rightMax)); }  // Create a binary tree let root = new Node(1); root.left = new Node(0); root.right = new Node(1); root.left.left = new Node(0); root.left.right = new Node(1); root.right.left = new Node(1); root.right.right = new Node(0);  // Find the maximum binary number in the tree let maxNumber = findMaxBinaryNumber(root, 0); console.log("Maximum Binary Number: " + maxNumber); 

Output
Maximum Binary Number: 7

Time Complexity: O(N)
Auxiliary Space: O(H), where H is height of binary tree.


Next Article
Maximum average of subtree values in a given Binary Tree
author
prasad264
Improve
Article Tags :
  • Tree
  • Geeks Premier League
  • DSA
  • Binary Tree
  • Geeks Premier League 2023
Practice Tags :
  • Tree

Similar Reads

  • Remove one bit from a binary number to get maximum value
    Given a binary number, the task is to remove exactly one bit from it such that, after it's removal, the resultant binary number is greatest from all the options.Examples: Input: 110 Output: 11 As 110 = 6 in decimal, the option is to remove either 0 or 1. So the possible combinations are 10, 11 The m
    4 min read
  • Find maximum (or minimum) in Binary Tree
    Given a Binary Tree, find the maximum(or minimum) element in it. For example, maximum in the following Binary Tree is 9. Recommended PracticeMax and min element in Binary TreeTry It! In Binary Search Tree, we can find maximum by traversing right pointers until we reach the rightmost node. But in Bin
    8 min read
  • Find maximum vertical sum in binary tree
    Given a binary tree, find the maximum vertical level sum in binary tree. Examples: Input : 3 / \ 4 6 / \ / \ -1 -2 5 10 \ 8 Output : 14Vertical level having nodes 6 and 8 has maximumvertical sum 14. Input : 1 / \ 5 8 / \ \ 2 -6 3 \ / -1 -4 \ 9Output : 4 A simple solution is to first find vertical le
    9 min read
  • Maximum width of a Binary Tree with null value
    Given a Binary Tree consisting of N nodes, the task is to find the maximum width of the given tree where the maximum width is defined as the maximum of all the widths at each level of the given Tree. The width of a tree for any level is defined as the number of nodes between the two extreme nodes of
    11 min read
  • Maximum average of subtree values in a given Binary Tree
    Given a Binary Tree consisting of N nodes, the task to find the maximum average of values of nodes of any subtree. Examples: Input: 5 / \ 3 8 Output: 8Explanation:Average of values of subtree of node 5 = (5 + 3 + 8) / 3 = 5.33Average of values of subtree of node 3 = 3 / 1 = 3Average of values of sub
    9 min read
  • Maximum in a Binary Search Tree
    Given a Binary Search Tree, the task is to find the node with the maximum value in a BST. Example: Input: Output : 7 Input: Output: 20 Table of Content [Naive Approach] Using Inorder Traversal – O(n) Time and O(n) Space[Expected Approach] Iterative Approach – O(n) Time and O(1) Space[Naive Approach]
    11 min read
  • Find maximum GCD value from root to leaf in a Binary tree
    Given a Binary Tree, the task is to find the maximum value of GCD from any path from the root node to the leaf node. Examples: Input: Below is the given tree: Output: 3Explanation:Path 1: 15->3->5 = gcd(15, 3, 15) =3Path 2: 15->3->1 =gcd(15, 3, 1) = 1Path 3: 15->7->31=gcd(15, 7, 31
    8 min read
  • Maximum width of a Binary Tree with null values | Set 2
    Pre-requisite: Maximum width of a Binary Tree with null value | Set 1 Given a Binary Tree consisting of N nodes, the task is to find the maximum width of the given tree without using recursion, where the maximum width is defined as the maximum of all the widths at each level of the given Tree. Note:
    8 min read
  • Maximum Path Sum in a Binary Tree
    Given a binary tree, the task is to find the maximum path sum. The path may start and end at any node in the tree. Example: Input: Output: 42Explanation: Max path sum is represented using green colour nodes in the above binary tree. Input: Output: 31Explanation: Max path sum is represented using gre
    9 min read
  • Maximum value at each level in an N-ary Tree
    Given a N-ary Tree consisting of nodes valued in the range [0, N - 1] and an array arr[] where each node i is associated to value arr[i], the task is to print the maximum value associated with any node at each level of the given N-ary Tree. Examples: Input: N = 8, Edges[][] = {{0, 1}, {0, 2}, {0, 3}
    9 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