Maximum number in Binary tree of binary values
Last Updated :
18 Jan, 2024
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);
OutputMaximum Binary Number: 7
Time Complexity: O(N)
Auxiliary Space: O(H), where H is height of binary tree.
Similar Reads
DSA Tutorial - Learn Data Structures and Algorithms
DSA (Data Structures and Algorithms) is the study of organizing data efficiently using data structures like arrays, stacks, and trees, paired with step-by-step procedures (or algorithms) to solve problems effectively. Data structures manage how data is stored and accessed, while algorithms focus on
7 min read
Non-linear Components
In electrical circuits, Non-linear Components are electronic devices that need an external power source to operate actively. Non-Linear Components are those that are changed with respect to the voltage and current. Elements that do not follow ohm's law are called Non-linear Components. Non-linear Co
11 min read
Quick Sort
QuickSort is a sorting algorithm based on the Divide and Conquer that picks an element as a pivot and partitions the given array around the picked pivot by placing the pivot in its correct position in the sorted array. It works on the principle of divide and conquer, breaking down the problem into s
12 min read
Merge Sort - Data Structure and Algorithms Tutorials
Merge sort is a popular sorting algorithm known for its efficiency and stability. It follows the divide-and-conquer approach. It works by recursively dividing the input array into two halves, recursively sorting the two halves and finally merging them back together to obtain the sorted array. Merge
14 min read
Bubble Sort Algorithm
Bubble Sort is the simplest sorting algorithm that works by repeatedly swapping the adjacent elements if they are in the wrong order. This algorithm is not suitable for large data sets as its average and worst-case time complexity are quite high.We sort the array using multiple passes. After the fir
8 min read
Breadth First Search or BFS for a Graph
Given a undirected graph represented by an adjacency list adj, where each adj[i] represents the list of vertices connected to vertex i. Perform a Breadth First Search (BFS) traversal starting from vertex 0, visiting vertices from left to right according to the adjacency list, and return a list conta
15+ min read
Data Structures Tutorial
Data structures are the fundamental building blocks of computer programming. They define how data is organized, stored, and manipulated within a program. Understanding data structures is very important for developing efficient and effective algorithms. What is Data Structure?A data structure is a st
2 min read
Binary Search Algorithm - Iterative and Recursive Implementation
Binary Search Algorithm is a searching algorithm used in a sorted array by repeatedly dividing the search interval in half. The idea of binary search is to use the information that the array is sorted and reduce the time complexity to O(log N). Binary Search AlgorithmConditions to apply Binary Searc
15 min read
Insertion Sort Algorithm
Insertion sort is a simple sorting algorithm that works by iteratively inserting each element of an unsorted list into its correct position in a sorted portion of the list. It is like sorting playing cards in your hands. You split the cards into two groups: the sorted cards and the unsorted cards. T
9 min read
Dijkstra's Algorithm to find Shortest Paths from a Source to all
Given a weighted undirected graph represented as an edge list and a source vertex src, find the shortest path distances from the source vertex to all other vertices in the graph. The graph contains V vertices, numbered from 0 to V - 1.Note: The given graph does not contain any negative edge. Example
12 min read