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
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 lev
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 : 7Input:Output: 20Table 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] Using
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 green
8 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
Find maximum level sum in Binary Tree Given a Binary Tree having positive and negative nodes, the task is to find the maximum sum level in it. Examples: Input : 4 / \ 2 -5 / \ /\ -1 3 -2 6Output: 6Explanation :Sum of all nodes of 0'th level is 4Sum of all nodes of 1'th level is -3Sum of all nodes of 0'th level is 6Hence maximum sum is 6
15+ min read