Given an integer N, the task is to print the modified binary tree pattern.
In Modified Binary Triangle Pattern, the first and last element of a Nth row are 1 and the middle (N – 2) elements are 0.
Input: N = 6
Input: N = 3
Approach: From the above examples, it can be observed that, for each row N:
- 1st and Nth element is a 1
- and elements 2 to (N-1) are 0
Therefore an algorithm can be developed to print such pattern as:
- Run a loop from 1 to N using a loop variable i, which denotes the row number of the triangle pattern.
- For each row i, run a loop from 1 to i, using a loop variable j, which denotes the number in each row.
- In each iteration of j, check if j is 1 or i. If either of it true, print 1.
- If none of the case is true for j, then print 0
- Increment the value of j by 1 after each iteration
- When the j loop has completed successfully, we have printed a row of the pattern. Therefore change the output to the next line by printing a next line.
- Increment the value of i and repeat the whole process till N rows has been printed successfully.
Below is the implementation of the above approach:
1 11 101 1001 10001 100001 1000001
Attention reader! Don’t stop learning now. Get hold of all the important DSA concepts with the DSA Self Paced Course at a student-friendly price and become industry ready.