Check if level-wise Decimal equivalent of Binary Tree forms a Monotonic sequence or not
Given the root of a binary tree in which all nodes has values either 0 or 1, the task is to check if the level-wise decimal equivalent of given Tree forms a monotonic sequence.or not.
A sequence is monotonic if it is either monotone increasing or monotone decreasing.
A sequence nums is monotone increasing if for all i <= j, nums[i] <= nums[j].
A sequence nums is monotone decreasing if for all i <= j, nums[i] >= nums[j].
Examples:
Input:
0
/ \
0 1
/ /
1 0
/ \
1 1
Output:
Yes
Explanation:
Level 0: 0 -> 0
Level 1: 01 -> 1
Level 2: 10 -> 2
Level 3: 11 -> 3
The sequence formed from the decimal equivalent of each level from root to leaf is {0, 1, 2, 3} which is a monotone increasing sequence.
Input:
1
/ \
1 1
/ /
1 0
/ \
0 1
Output:
No
Approach:
The idea is to perform levelorder traversal of given Tree and for each level, convert the binary representation to decimal and store in an int variable. Then the problem will be converted to simply check if given array is a monotonic sequence or not.
Follow the below steps to solve this problem:
- Do level order traversal from root to leaf
- For each level, convert it to decimal equivalent and store the value in an integer array
- Then check whether the given array is monotonic increasing or decreasing
Below is the implementation of the above approach:
C++
#include <iostream> #include <vector> #include <string> using namespace std; // Class containing left and right // child of current node and key value class Node { public : int data; Node* left; Node* right; Node( int item) { data = item; left = right = nullptr; } }; class GFG { // Root of the Binary Tree public : Node* root; bool checkMonotonic(Node* root) { vector< int > sequenceArray = getLevelOrderArray(root); bool increasing = true ; bool decreasing = true ; for ( int i = 0; i < sequenceArray.size() - 1; ++i) { if (sequenceArray[i] > sequenceArray[i + 1]) increasing = false ; if (sequenceArray[i] < sequenceArray[i + 1]) decreasing = false ; } return increasing || decreasing; } vector< int > getLevelOrderArray(Node* root) { int h = height(root); int i; vector< int > retVal; for (i = 1; i <= h; i++) { vector< int > currentLevel; auto currentLevelOrder = getCurrentLevel(root, i, currentLevel); string binaryString = "" ; for ( auto val : currentLevelOrder) { binaryString += to_string(val); } retVal.push_back(stoi(binaryString, nullptr, 2)); } return retVal; } // Compute the "height" of a tree -- // the number of nodes along the longest // path from the root node down to the // farthest leaf node. int height(Node* root) { if (root == nullptr) { return 0; } else { // compute height of each subtree int lheight = height(root->left); int rheight = height(root->right); // use the larger one if (lheight > rheight) { return (lheight + 1); } else { return (rheight + 1); } } } // Get nodes at the current level vector< int > getCurrentLevel(Node* root, int level, vector< int >& currentLevelOrder) { if (root == nullptr) { return currentLevelOrder; } if (level == 1) { currentLevelOrder.push_back(root->data); } else if (level > 1) { getCurrentLevel(root->left, level - 1, currentLevelOrder); getCurrentLevel(root->right, level - 1, currentLevelOrder); } return currentLevelOrder; } }; // Driver Code int main() { GFG tree; tree.root = new Node(0); tree.root->left = new Node(0); tree.root->right = new Node(1); tree.root->left->left = new Node(1); tree.root->right->left = new Node(0); tree.root->right->left->left = new Node(1); tree.root->right->left->right = new Node(1); bool ans = tree.checkMonotonic(tree.root); if (ans) cout << "Yes" ; else cout << "No" ; return 0; } |
Java
// Java code to check if the tree is monotonic import java.io.*; import java.util.*; // Class containing left and right // child of current node and key value class Node { public int data; public Node left, right; public Node( int item) { data = item; left = right = null ; } } class GFG { // Root of the Binary Tree public Node root; public boolean checkMonotonic(Node root) { int [] sequenceArray = getLevelOrderArray(root); boolean increasing = true ; boolean decreasing = true ; for ( int i = 0 ; i < sequenceArray.length - 1 ; ++i) { if (sequenceArray[i] > sequenceArray[i + 1 ]) increasing = false ; if (sequenceArray[i] < sequenceArray[i + 1 ]) decreasing = false ; } return increasing || decreasing; } public int [] getLevelOrderArray(Node root) { int h = height(root); int i; List<Integer> retVal = new ArrayList<>(); for (i = 1 ; i <= h; i++) { List<Integer> currentLevel = new ArrayList<>(); var currentLevelOrder = getCurrentLevel(root, i, currentLevel) .toArray( new Integer[ 0 ]); StringBuilder sb = new StringBuilder(); for ( int j = 0 ; j < currentLevelOrder.length; j++) { sb.append(currentLevelOrder[j]); } retVal.add(Integer.parseInt(sb.toString(), 2 )); } int [] retArr = new int [retVal.size()]; for ( int j = 0 ; j < retVal.size(); j++) { retArr[j] = retVal.get(j); } return retArr; } // Compute the "height" of a tree -- // the number of nodes along the longest // path from the root node down to the // farthest leaf node. public int height(Node root) { if (root == null ) { return 0 ; } else { // compute height of each subtree int lheight = height(root.left); int rheight = height(root.right); // use the larger one if (lheight > rheight) { return (lheight + 1 ); } else { return (rheight + 1 ); } } } // Get nodes at the current level public List<Integer> getCurrentLevel(Node root, int level, List<Integer> currentLevelOrder) { if (root == null ) { return currentLevelOrder; } if (level == 1 ) { currentLevelOrder.add(root.data); } else if (level > 1 ) { getCurrentLevel(root.left, level - 1 , currentLevelOrder); getCurrentLevel(root.right, level - 1 , currentLevelOrder); } return currentLevelOrder; } public static void main(String[] args) { GFG tree = new GFG(); tree.root = new Node( 0 ); tree.root.left = new Node( 0 ); tree.root.right = new Node( 1 ); tree.root.left.left = new Node( 1 ); tree.root.right.left = new Node( 0 ); tree.root.right.left.left = new Node( 1 ); tree.root.right.left.right = new Node( 1 ); boolean ans = tree.checkMonotonic(tree.root); if (ans) System.out.print( "Yes" ); else System.out.print( "No" ); } } // This code is contributed by lokesh. |
Python3
# Python code to check if the tree is monotonic # Class containing left and right child # of current node and key value class Node: def __init__( self , item): self .data = item self .left = None self .right = None class GFG: # Root of the Binary Tree def __init__( self ): self .root = None def check_monotonic( self , root): sequence_array = self .get_level_order_array(root) increasing = True decreasing = True for i in range ( len (sequence_array) - 1 ): if sequence_array[i] > sequence_array[i + 1 ]: increasing = False if sequence_array[i] < sequence_array[i + 1 ]: decreasing = False return increasing or decreasing def get_level_order_array( self , root): h = self .height(root) ret_val = [] for i in range ( 1 , h + 1 ): current_level = [] current_level_order = self .get_current_level(root, i, current_level) ret_val.append( int (''.join( map ( str , current_level_order)), 2 )) return ret_val def height( self , root): if root is None : return 0 else : lheight = self .height(root.left) rheight = self .height(root.right) if lheight > rheight: return lheight + 1 else : return rheight + 1 def get_current_level( self , root, level, current_level_order): if root is None : return current_level_order if level = = 1 : current_level_order.append(root.data) elif level > 1 : self .get_current_level(root.left, level - 1 , current_level_order) self .get_current_level(root.right, level - 1 , current_level_order) return current_level_order tree = GFG() tree.root = Node( 0 ) tree.root.left = Node( 0 ) tree.root.right = Node( 1 ) tree.root.left.left = Node( 1 ) tree.root.right.left = Node( 0 ) tree.root.right.left.left = Node( 1 ) tree.root.right.left.right = Node( 1 ) if tree.check_monotonic(tree.root): print ( "Yes" ) else : print ( "No" ) # This code is contributed by lokeshmvs21. |
Javascript
<script> // Class containing left and right // child of current node and key value class Node { constructor(val) { this .key = val; this .left = null ; this .right = null ; } } function checkMonotonic(root) { let sequenceArray = getLevelOrderArray(root); let increasing = true ; let decreasing = true ; for (let i = 0; i < sequenceArray.length - 1; ++i) { if (sequenceArray[i] > sequenceArray[i + 1]) increasing = false ; if (sequenceArray[i] < sequenceArray[i + 1]) decreasing = false ; } return increasing || decreasing; } function getLevelOrderArray(root) { let h = height(root); let i; let retVal = []; for (i = 1; i <= h; i++) { let currentLevel = []; let currentLevelOrder = getCurrentLevel(root, i, currentLevel); retVal.push(parseInt( currentLevelOrder.join( "" ))); } return retVal; } // Compute the "height" of a tree -- // the number of nodes along the longest // path from the root node down to the // farthest leaf node. function height(root) { if (root == null ) { return 0; } else { // compute height of each subtree let lheight = height(root.left); let rheight = height(root.right); // use the larger one if (lheight > rheight) { return (lheight + 1); } else { return (rheight + 1); } } } // Get nodes at the current level function getCurrentLevel( root, level, currentLevelOrder) { if (root == null ) { return currentLevelOrder; } if (level == 1) { currentLevelOrder.push(root.data); } else if (level > 1) { getCurrentLevel(root.left, level - 1, currentLevelOrder); getCurrentLevel(root.right, level - 1, currentLevelOrder); } return currentLevelOrder; } // Driver Code // Root of the Binary Tree let root = new Node(0);; root.left = new Node(0); root.right = new Node(1); root.left.left = new Node(1); root.right.left = new Node(0); root.right.left.left = new Node(1); root.right.left.right = new Node(1); let ans = checkMonotonic(root); if (ans) console.log( "Yes" ); else console.log( "No" ); // This code is contributed by akashish___ </script> |
C#
// C# code to check if the tree is monotonic using System; using System.Collections.Generic; using System.Linq; // Class containing left and right // child of current node and key value public class Node { public int data; public Node left, right; public Node( int item) { data = item; left = right = null ; } } public class GFG { // Root of the Binary Tree public Node root; public virtual bool checkMonotonic(Node root) { int [] sequenceArray = getLevelOrderArray(root); bool increasing = true ; bool decreasing = true ; for ( int i = 0; i < sequenceArray.Length - 1; ++i) { if (sequenceArray[i] > sequenceArray[i + 1]) increasing = false ; if (sequenceArray[i] < sequenceArray[i + 1]) decreasing = false ; } return increasing || decreasing; } public virtual int [] getLevelOrderArray(Node root) { int h = height(root); int i; List< int > retVal = new List< int >(); for (i = 1; i <= h; i++) { List< int > currentLevel = new List< int >(); var currentLevelOrder = getCurrentLevel(root, i, currentLevel) .ToList(); retVal.Add(Convert.ToInt32( string .Join( "" , currentLevelOrder), 2)); } return retVal.ToArray(); } // Compute the "height" of a tree -- // the number of nodes along the longest // path from the root node down to the // farthest leaf node. public virtual int height(Node root) { if (root == null ) { return 0; } else { // compute height of each subtree int lheight = height(root.left); int rheight = height(root.right); // use the larger one if (lheight > rheight) { return (lheight + 1); } else { return (rheight + 1); } } } // Get nodes at the current level public virtual IList< int > getCurrentLevel(Node root, int level, List< int > currentLevelOrder) { if (root == null ) { return currentLevelOrder; } if (level == 1) { currentLevelOrder.Add(root.data); } else if (level > 1) { getCurrentLevel(root.left, level - 1, currentLevelOrder); getCurrentLevel(root.right, level - 1, currentLevelOrder); } return currentLevelOrder; } // Driver Code public static void Main( string [] args) { GFG tree = new GFG(); tree.root = new Node(0); tree.root.left = new Node(0); tree.root.right = new Node(1); tree.root.left.left = new Node(1); tree.root.right.left = new Node(0); tree.root.right.left.left = new Node(1); tree.root.right.left.right = new Node(1); bool ans = tree.checkMonotonic(tree.root); if (ans) Console.Write( "Yes" ); else Console.Write( "No" ); } } |
Yes
Time Complexity: O(N^2)
Auxiliary Space: O(N+L), where L is the count of levels in Tree, which will the size of Array to store decimal value of each level
Efficient Approach: The auxiliary space in the above approach can be optimised by just looking at adjacent levels and checking they follow monotonic sequence or not.
Instead of storing the decimal equivalent of each level in a array and then check the array for monotonic, we can check the increasing/decreasing nature of each level as we traverse it. This way, we can terminate as soon as we get a value that breaks the monotonicity. For this to work, we will need to store the value of previous level to compare with the next level.
Below is the implementation of the above approach:
C++
// C++ code for the above approach #include <iostream> #include <queue> #include <bitset> using namespace std; // Class containing left and right child of current node and key value class Node { public : int data; Node* left; Node* right; Node( int item) { data = item; left = right = nullptr; } }; class GFG { public : // Root of the Binary Tree Node* root; GFG() { root = nullptr; } bool checkMonotonic(Node* root) { int h = height(root); int i = 1; int prevLevelValue = bitset<8>(root->data).to_ulong(); bool increasing = true ; bool decreasing = true ; while (i <= h) { vector< int > currentLevelOrder; getCurrentLevel(root, i, currentLevelOrder); int currentLevelValue = bitset<8>(0).to_ulong(); for ( int j = 0; j < currentLevelOrder.size(); j++) { currentLevelValue |= (currentLevelOrder[j] << (currentLevelOrder.size() - j - 1)); } if (prevLevelValue > currentLevelValue) { increasing = false ; } if (prevLevelValue < currentLevelValue) { decreasing = false ; } prevLevelValue = currentLevelValue; i++; } return increasing || decreasing; } // Compute the "height" of a tree -- // the number of nodes along the longest // path from the root node down to the // farthest leaf node. int height(Node* root) { if (root == nullptr) { return 0; } else { int lheight = height(root->left); int rheight = height(root->right); if (lheight > rheight) { return (lheight + 1); } else { return (rheight + 1); } } } // Get nodes at the current level void getCurrentLevel(Node* root, int level, vector< int >& currentLevelOrder) { if (root == nullptr) { return ; } if (level == 1) { currentLevelOrder.push_back(root->data); } else if (level > 1) { getCurrentLevel(root->left, level - 1, currentLevelOrder); getCurrentLevel(root->right, level - 1, currentLevelOrder); } } }; int main() { GFG tree; tree.root = new Node(0); tree.root->left = new Node(0); tree.root->right = new Node(1); tree.root->left->left = new Node(1); tree.root->right->left = new Node(0); tree.root->right->left->left = new Node(1); tree.root->right->left->right = new Node(1); bool ans = tree.checkMonotonic(tree.root); if (ans) { cout << "Yes" << endl; } else { cout << "No" << endl; } return 0; } // This code is contributed by sdeadityasharma |
Java
// Java code to implement the above approach import java.io.*; import java.util.*; // Class containing left and right child of current node and // key value class Node { int data; Node left, right; Node( int item) { data = item; left = right = null ; } } class GFG { // Root of the Binary Tree Node root; public boolean checkMonotonic(Node root) { int h = height(root); int i; int prevLevelValue = Integer.parseInt( Integer.toBinaryString(root.data), 2 ); boolean increasing = true ; boolean decreasing = true ; for (i = 1 ; i <= h; i++) { List<Integer> currentLevel = new ArrayList<>(); List<Integer> currentLevelOrder = getCurrentLevel(root, i, currentLevel); int currentLevelValue = Integer.parseInt( currentLevelOrder.stream() .map(Object::toString) .reduce( "" , (a, b) -> a + b), 2 ); if (prevLevelValue > currentLevelValue) increasing = false ; if (prevLevelValue < currentLevelValue) decreasing = false ; prevLevelValue = currentLevelValue; } return increasing || decreasing; } // Compute the "height" of a tree -- // the number of nodes along the longest // path from the root node down to the // farthest leaf node. static int height(Node root) { if (root == null ) { return 0 ; } else { int lheight = height(root.left); int rheight = height(root.right); if (lheight > rheight) { return (lheight + 1 ); } else { return (rheight + 1 ); } } } // Get nodes at the current level static List<Integer> getCurrentLevel(Node root, int level, List<Integer> currentLevelOrder) { if (root == null ) { return currentLevelOrder; } if (level == 1 ) { currentLevelOrder.add(root.data); } else if (level > 1 ) { getCurrentLevel(root.left, level - 1 , currentLevelOrder); getCurrentLevel(root.right, level - 1 , currentLevelOrder); } return currentLevelOrder; } public static void main(String[] args) { GFG tree = new GFG(); tree.root = new Node( 0 ); tree.root.left = new Node( 0 ); tree.root.right = new Node( 1 ); tree.root.left.left = new Node( 1 ); tree.root.right.left = new Node( 0 ); tree.root.right.left.left = new Node( 1 ); tree.root.right.left.right = new Node( 1 ); boolean ans = tree.checkMonotonic(tree.root); if (ans) System.out.println( "Yes" ); else System.out.println( "No" ); } } // This code is contributed by karthik |
C#
// C# code to implement the above approach using System; using System.Collections.Generic; using System.Linq; // Class containing left and right // child of current node and key value public class Node { public int data; public Node left, right; public Node( int item) { data = item; left = right = null ; } } public class GFG { // Root of the Binary Tree public Node root; public virtual bool checkMonotonic(Node root) { int h = height(root); int i; int prevLevelValue = Convert.ToInt32(root.data.ToString(), 2); bool increasing = true ; bool decreasing = true ; for (i = 1; i <= h; i++) { List< int > currentLevel = new List< int >(); var currentLevelOrder = getCurrentLevel(root, i, currentLevel) .ToList(); int currentLevelValue = Convert.ToInt32( string .Join( "" , currentLevelOrder), 2); if (prevLevelValue > currentLevelValue) increasing = false ; if (prevLevelValue < currentLevelValue) decreasing = false ; prevLevelValue = currentLevelValue; } return increasing || decreasing; } // Compute the "height" of a tree -- // the number of nodes along the longest // path from the root node down to the // farthest leaf node. public virtual int height(Node root) { if (root == null ) { return 0; } else { // compute height of each subtree int lheight = height(root.left); int rheight = height(root.right); /* use the larger one */ if (lheight > rheight) { return (lheight + 1); } else { return (rheight + 1); } } } // Get nodes at the current level public virtual IList< int > getCurrentLevel(Node root, int level, List< int > currentLevelOrder) { if (root == null ) { return currentLevelOrder; } if (level == 1) { currentLevelOrder.Add(root.data); } else if (level > 1) { getCurrentLevel(root.left, level - 1, currentLevelOrder); getCurrentLevel(root.right, level - 1, currentLevelOrder); } return currentLevelOrder; } // Driver Code public static void Main( string [] args) { GFG tree = new GFG(); tree.root = new Node(0); tree.root.left = new Node(0); tree.root.right = new Node(1); tree.root.left.left = new Node(1); tree.root.right.left = new Node(0); tree.root.right.left.left = new Node(1); tree.root.right.left.right = new Node(1); bool ans = tree.checkMonotonic(tree.root); if (ans) Console.Write( "Yes" ); else Console.Write( "No" ); } } |
Javascript
<script> // JavaScript code to implement the above approach // Class containing left and right child of current node and key value class Node { constructor(data) { this .data = data; this .left = null ; this .right = null ; } } class GFG { constructor() { // Root of the binary tree this .root = null ; } checkMonotonic(root) { let h = this .height(root); let prevLevelValue = parseInt(root.data.toString(2), 2); let increasing = true ; let decreasing = true ; for (let i = 1; i <= h; i++) { let currentLevel = []; let currentLevelOrder = this .getCurrentLevel(root, i, currentLevel); let currentLevelValue = parseInt(currentLevelOrder.join( '' ), 2); if (prevLevelValue > currentLevelValue) increasing = false ; if (prevLevelValue < currentLevelValue) decreasing = false ; prevLevelValue = currentLevelValue; } return increasing || decreasing; } // Compute the "height" of a tree -- the number of nodes along the // longest path from the root node down to the farthest leaf node. height(root) { if (!root) { return 0; } else { let lheight = this .height(root.left); let rheight = this .height(root.right); if (lheight > rheight) { return lheight + 1; } else { return rheight + 1; } } } // Get nodes at the current level getCurrentLevel(root, level, currentLevelOrder) { if (!root) { return currentLevelOrder; } if (level === 1) { currentLevelOrder.push(root.data); } else if (level > 1) { this .getCurrentLevel(root.left, level - 1, currentLevelOrder); this .getCurrentLevel(root.right, level - 1, currentLevelOrder); } return currentLevelOrder; } } let tree = new GFG(); tree.root = new Node(0); tree.root.left = new Node(0); tree.root.right = new Node(1); tree.root.left.left = new Node(1); tree.root.right.left = new Node(0); tree.root.right.left.left = new Node(1); tree.root.right.left.right = new Node(1); let ans = tree.checkMonotonic(tree.root); if (ans) { document.write( "Yes" ); } else { document.write( "No" ); } // This code is contributed by lokesh. </script> |
Python3
# Python code to implement the above approach import queue # Class containing left and right child of current node and key value class Node: def __init__( self , item): self .data = item self .left = None self .right = None class GFG: # Root of the Binary Tree def __init__( self ): self .root = None def checkMonotonic( self , root): h = self .height(root) i = 1 prevLevelValue = int ( format (root.data, "b" )) increasing = True decreasing = True while i < = h: currentLevel = [] currentLevelOrder = self .getCurrentLevel(root, i, currentLevel) currentLevelValue = int ("".join( str (x) for x in currentLevelOrder), 2 ) if prevLevelValue > currentLevelValue: increasing = False if prevLevelValue < currentLevelValue: decreasing = False prevLevelValue = currentLevelValue i + = 1 return increasing or decreasing # Compute the "height" of a tree -- # the number of nodes along the longest # path from the root node down to the # farthest leaf node. def height( self , root): if root is None : return 0 else : lheight = self .height(root.left) rheight = self .height(root.right) if lheight > rheight: return (lheight + 1 ) else : return (rheight + 1 ) # Get nodes at the current level def getCurrentLevel( self , root, level, currentLevelOrder): if root is None : return currentLevelOrder if level = = 1 : currentLevelOrder.append(root.data) elif level > 1 : self .getCurrentLevel(root.left, level - 1 , currentLevelOrder) self .getCurrentLevel(root.right, level - 1 , currentLevelOrder) return currentLevelOrder if __name__ = = "__main__" : tree = GFG() tree.root = Node( 0 ) tree.root.left = Node( 0 ) tree.root.right = Node( 1 ) tree.root.left.left = Node( 1 ) tree.root.right.left = Node( 0 ) tree.root.right.left.left = Node( 1 ) tree.root.right.left.right = Node( 1 ) ans = tree.checkMonotonic(tree.root) if ans: print ( "Yes" ) else : print ( "No" ) |
Yes
Time Complexity: O(N^2)
Auxiliary Space: O(N)
Contact Us