![]() |
VOOZH | about |
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:
Below is the implementation of the above approach:
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:
Yes
Time Complexity: O(N^2)
Auxiliary Space: O(N)