Reverse Level Order Traversal of Binary Tree in Java

Reverse Level Order Traversal of Binary Tree in Java 


Print reverse level order traversal of binary tree. Let us first understand what we want to achieve? what is the input and what will be the expected output?

Find Height of Binary Tree in Java.

Find Height of Binary Tree OR Find the Maximum Depth of Binary Tree.


Given a binary tree, Find the height of tree.

Let's understand what is the input and expected output.


Merge sort explanation in java

Merge sort Algorithm in java.


Given a unsorted array, Sort it using Merge Sort Algorithm.

Lets understand what is the input and the expected output.

sort array using merge sort in java
Sort array using merge sort in java

Merge sort Algorithm


How Merge Sort works
  1. Merge Sort works by breaking the array into 2 equal parts say Left half and Right half.
  2. Again break 2 sub array that we got in Step 1 in two equal parts each.  
  3. Repeat above steps until only 1 element remains in array because array with only one element is always sorted. 
  4. So in each step we are breaking the array in Left half and Right half.  
  5. When complete array is divided and contains only Single element in Left and Right half each, Start comparing and sort each Left and Right half, So that portion of array will be sorted.
  6. Repeat Step 5 for all the remaining Left and Right sub-array and complete array will be sorted.

Merge sort Time complexity


Merge sort time complexity is O(N log N).

Lets understand with the help of below example.

merge sort algorithm with example
Merge sort algorithm with example

Java program to sort an array using merge sort


package com.javabypatel;

public class MergeSort {

    public static void main(String[] args) {
        int arr[] = {10, 1, -2, 8, 9, 10, 1};

        //Before sort
        print(arr);

        mergeSort(arr, 0, arr.length - 1);

        //After sort
        print(arr);
    }

    static void mergeSort(int arr[], int start, int end) {
        if (start >= end)
            return;

        int mid = start + (end - start) / 2;
        mergeSort(arr, start, mid);
        mergeSort(arr, mid + 1, end);
        merge(arr, start, mid, end);
    }

    static void merge(int[] arr, int start, int mid, int end) {
        int i = start;
        int j = mid + 1;
        int counter = 0;

        int[] tempArr = new int[(end - start) + 1];

        while (i <= mid && j <= end) {
            if (arr[j] < arr[i]) {
                tempArr[counter] = arr[j];
                j++;
            } else {
                tempArr[counter] = arr[i];
                i++;
            }
            counter++;
        }
        while (i <= mid) {
            tempArr[counter] = arr[i];
            i++;
            counter++;
        }

        while (j <= end) {
            tempArr[counter] = arr[j];
            j++;
            counter++;
        }

        for (int k = 0; k < counter; k++) {
            arr[start + k] = tempArr[k];
        }
    }

    static void print(int arr[]) {
        for (int i = 0; i < arr.length; i++) {
            System.out.print(arr[i] + " ");
        }
        System.out.println();
    }
}

You may also like to see


Sort Linked list using Merge sort

Bubble Sort

Heap Sort

Selection Sort

Insertion Sort


How ConcurrentHashMap works and ConcurrentHashMap interview questions

How Much Water Can A Bar Graph with different heights can Hold

Interview Questions-Answer Bank

Enjoy !!!! 

If you find any issue in post or face any error while implementing, Please comment.

Reverse linked list using recursion in Java

Reverse linked list using recursion OR Reverse linked list recursively .


Let's see, how to Reverse a linked list recursively in Java

There are 2 ways to Reverse a Linked list using,

1. Recursive Algorithm.
2. Iterative Algorithm.

 Lets understand what is the input and the expected output.

Java 8 Stream Practice Problems

Java 8 Stream Practice Problems


Java 8 Stream API is very useful for filtering collections. Lets see few java 8 stream practice questions.
Scenario

By looking at below example class, answer the following questions, 
  1. Get student with exact match name "jayesh"
  2. Get student with matching address "1235"
  3. Get all student having mobile numbers 3333.
  4. Get all student having mobile number 1233 and 1234
  5. Create a List<Student> from the List<TempStudent>
  6. Convert List<Student> to List<String> of student name
  7. Convert List<students> to String
  8. Change the case of List<String>
  9. Sort List<String>
  10. Conditionally apply Filter condition, say if flag is enabled then.

package com.javabypatel; 

class TempStudent {
    public String name;
    public int age;
    public Address address;
    public List<MobileNumber> mobileNumbers;

    public TempStudent(String name, int age, Address address, List<MobileNumber> mobileNumbers) {
        this.name = name;
        this.age = age;
        this.address = address;
        this.mobileNumbers = mobileNumbers;
    }
}

class Student{
    private String name;
    private int age;
    private Address address;
    private List<MobileNumber> mobileNumbers;

    public Student(String name, int age, Address address, List<MobileNumber> mobileNumbers) {
        this.name = name;
        this.age = age;
        this.address = address;
        this.mobileNumbers = mobileNumbers;
    }

    public String getName() {
        return name;
    }

    public int getAge() {
        return age;
    }

    public Address getAddress() {
        return address;
    }

    public List<MobileNumber> getMobileNumbers() {
        return mobileNumbers;
    }

    public void setName(String name) {
        this.name = name;
    }

    public void setAge(int age) {
        this.age = age;
    }

    public void setAddress(Address address) {
        this.address = address;
    }

    public void setMobileNumbers(List<MobileNumber> mobileNumbers) {
        this.mobileNumbers = mobileNumbers;
    }

    @Override
    public String toString() {
        return "Student{" +
            "name='" + name + '\'' +
            ", age=" + age +
            ", address=" + address +
            ", mobileNumbers=" + mobileNumbers +
            '}';
    }
}

class Address{
    private String zipcode;

    public Address(String zipcode) {
        this.zipcode = zipcode;
    }

    public String getZipcode() {
        return zipcode;
    }

    public void setZipcode(String zipcode) {
        this.zipcode = zipcode;
    }
}

class MobileNumber{
    private String number;

    public MobileNumber(String number) {
        this.number = number;
    }

    public String getNumber() {
        return number;
    }

    public void setNumber(String number) {
        this.number = number;
    }
}

Solution

package com.javabypatel;

import java.util.Arrays;
import java.util.Comparator;
import java.util.List;
import java.util.Objects;
import java.util.Optional;
import java.util.stream.Collectors;
import java.util.stream.Stream;

public class StreamTest {
    public static void main(String[] args) {

        Student student1 = new Student(
            "Jayesh",
            20,
            new Address("1234"),
            Arrays.asList(new MobileNumber("1233"), new MobileNumber("1234")));

        Student student2 = new Student(
            "Khyati",
            20,
            new Address("1235"),
            Arrays.asList(new MobileNumber("1111"), new MobileNumber("3333"), new MobileNumber("1233")));

        Student student3 = new Student(
            "Jason",
            20,
            new Address("1236"),
            Arrays.asList(new MobileNumber("3333"), new MobileNumber("4444")));

        List<Student> students = Arrays.asList(student1, student2, student3);

        /*****************************************************
         Get student with exact match name "jayesh"
        *****************************************************/
        Optional<Student> stud = students.stream()
            .filter(student -> student.getName().equals("Jayesh"))
            .findFirst();
        System.out.println(stud.isPresent() ? stud.get().getName() : "No student found");
        System.out.println("--------------------");

        /*****************************************************
         Get student with matching address "1235"
        *****************************************************/
        Optional<Student> stud1 = students.stream()
            .filter(student -> student.getAddress().getZipcode().equals("1235"))
            .findFirst();
        System.out.println(stud1.isPresent() ? stud1.get().getName() : "No student found");
        System.out.println("--------------------");

        /*****************************************************
         Get all student having mobile numbers 3333.
        *****************************************************/
        List<Student> stud2 = students.stream()
            .filter(student111 -> student111.getMobileNumbers().stream().anyMatch(x -> Objects.equals(x.getNumber(), "3333")))
            .collect(Collectors.toList());

          String result1 = stud2.stream().map(std -> std.getName()).collect(Collectors.joining(",", "[", "]"));
          System.out.println(result1);
        System.out.println("--------------------");

        /*****************************************************
         Get all student having mobile number 1233 and 1234
         *****************************************************/
        List<Student> stud3 = students.stream()
            .filter(student -> student.getMobileNumbers().stream().allMatch(x -> Objects.equals(x.getNumber(), "1233") || Objects.equals(x.getNumber(), "1234")))
            .collect(Collectors.toList());

        String result4 = stud3.stream().map(std -> std.getName()).collect(Collectors.joining(",", "[", "]"));
        System.out.println(result4);
        System.out.println("--------------------");

        /*****************************************************
         Create a List<Student> from the List<TempStudent>
        *****************************************************/
        TempStudent tmpStud1 = new TempStudent(
            "Jayesh1",
            201,
            new Address("12341"),
            Arrays.asList(new MobileNumber("12331"), new MobileNumber("12341")));

        TempStudent tmpStud2 = new TempStudent(
            "Khyati1",
            202,
            new Address("12351"),
            Arrays.asList(new MobileNumber("11111"), new MobileNumber("33331"), new MobileNumber("12331")));

        List<TempStudent> tmpStudents = Arrays.asList(tmpStud1, tmpStud2);

        List<Student> studentList = tmpStudents.stream()
            .map(tmpStud -> new Student(tmpStud.name, tmpStud.age, tmpStud.address, tmpStud.mobileNumbers))
            .collect(Collectors.toList());

        System.out.println(studentList);
        System.out.println("--------------------");

        /*****************************************************
         Convert List<Student> to List<String> of student name
        *****************************************************/
        List<String> studentsName = studentList.stream()
            .map(Student::getName)
            .collect(Collectors.toList());

        System.out.println(studentsName.stream().collect(Collectors.joining(",")));
        System.out.println(studentsName.stream().collect(Collectors.joining(",", "[", "]")));
        System.out.println("--------------------");

        /*****************************************************
         Convert List<students> to String
        *****************************************************/
        String name = students.stream()
            .map(Student::getName)
            .collect(Collectors.joining(",", "[", "]"));
        System.out.println(name);
        System.out.println("--------------------");

        /*****************************************************
         Change the case of List<String>
        *****************************************************/
        List<String> nameList =
            Arrays.asList("Jayesh", "Dany", "Khyati", "Hello", "Mango");

        nameList.stream()
            .map(String::toUpperCase)
            .forEach(System.out::println);
        System.out.println("--------------------");

        /*****************************************************
         Sort List<String>
         *****************************************************/
        List<String> namesList =
            Arrays.asList("Jayesh", "Dany", "Khyati", "Hello", "Mango");

        namesList.stream()
            .sorted()
            .forEach(System.out::println);
        System.out.println("--------------------");

        /*****************************************************
         Conditionally apply Filter condition, say if flag is enabled then
         *****************************************************/
        boolean sortConditionFlag = true;

        Stream<Student> conditionalFilterResult = students.stream()
            .filter(std -> std.getName().startsWith("J"));

        if(sortConditionFlag){
            conditionalFilterResult = conditionalFilterResult.sorted(Comparator.comparing(Student::getName));
        }

        System.out.println("Before sorting :");
        students.forEach(s -> System.out.println(s.getName()));

        List<Student> list = conditionalFilterResult.collect(Collectors.toList());
        System.out.println("After filter and conditional sorting :");
        list.forEach(s -> System.out.println(s.getName()));

    }
}

Output
Jayesh
--------------------
Khyati
--------------------
[Khyati,Jason]
--------------------
[Jayesh]
--------------------
[Student{name='Jayesh1', age=201, address=com.javabypatel.sea.Address@685cb137, mobileNumbers=[com.javabypatel.sea.MobileNumber@6a41eaa2, com.javabypatel.sea.MobileNumber@7cd62f43]},

Student{name='Khyati1', age=202, address=com.javabypatel.sea.Address@6d4b1c02, mobileNumbers=[com.javabypatel.sea.MobileNumber@6093dd95, com.javabypatel.sea.MobileNumber@5622fdf, com.javabypatel.sea.MobileNumber@4883b407]}]
--------------------
Jayesh1,Khyati1
[Jayesh1,Khyati1]
--------------------
[Jayesh,Khyati,Jason]
--------------------
JAYESH
DANY
KHYATI
HELLO
MANGO
--------------------
Dany
Hello
Jayesh
Khyati
Mango
--------------------
Before sorting :
Jayesh
Khyati
Jason
After filter and conditional sorting :
Jason
Jayesh

When to use Interface in java with example

Interface Vs Abstract class in Java OOPS.

Top Java Interface Interview Questions and Answers

When to use interface and abstract class in Java? what is the difference between them?

Java Multithreading and Concurrency Interview Questions and Answers with Example

Advanced Multithreading Interview Questions In Java

How ConcurrentHashMap works and ConcurrentHashMap interview questions.

Enjoy !!!! 
If you find any issue in post or face any error while implementing, Please comment.

Java 8 Stream Filter examples

Java 8 Stream Filter examples


Java 8 Stream API is very useful for filtering collections. Lets see example of java 8 filter API
Scenario

class TempStudent {
    public String name;
    public int age;
    public Address address;
    public List<MobileNumber> mobileNumbers;

    public TempStudent(String name, int age, Address address, List<MobileNumber> mobileNumbers) {
        this.name = name;
        this.age = age;
        this.address = address;
        this.mobileNumbers = mobileNumbers;
    }
}

class Student{
    private String name;
    private int age;
    private Address address;
    private List<MobileNumber> mobileNumbers;

    public Student(String name, int age, Address address, List<MobileNumber> mobileNumbers) {
        this.name = name;
        this.age = age;
        this.address = address;
        this.mobileNumbers = mobileNumbers;
    }

    public String getName() {
        return name;
    }

    public int getAge() {
        return age;
    }

    public Address getAddress() {
        return address;
    }

    public List<MobileNumber> getMobileNumbers() {
        return mobileNumbers;
    }

    public void setName(String name) {
        this.name = name;
    }

    public void setAge(int age) {
        this.age = age;
    }

    public void setAddress(Address address) {
        this.address = address;
    }

    public void setMobileNumbers(List<MobileNumber> mobileNumbers) {
        this.mobileNumbers = mobileNumbers;
    }

    @Override
    public String toString() {
        return "Student{" +
            "name='" + name + '\'' +
            ", age=" + age +
            ", address=" + address +
            ", mobileNumbers=" + mobileNumbers +
            '}';
    }
}

class Address{
    private String zipcode;

    public Address(String zipcode) {
        this.zipcode = zipcode;
    }

    public String getZipcode() {
        return zipcode;
    }

    public void setZipcode(String zipcode) {
        this.zipcode = zipcode;
    }
}

class MobileNumber{
    private String number;

    public MobileNumber(String number) {
        this.number = number;
    }

    public String getNumber() {
        return number;
    }

    public void setNumber(String number) {
        this.number = number;
    }
}



Scenario

package com.javabypatel;

import java.util.Arrays;
import java.util.Comparator;
import java.util.List;
import java.util.Objects;
import java.util.Optional;
import java.util.stream.Collectors;
import java.util.stream.Stream;

public class StreamTest {
    public static void main(String[] args) {

        Student student1 = new Student(
            "Jayesh",
            20,
            new Address("1234"),
            Arrays.asList(new MobileNumber("1233"), new MobileNumber("1234")));

        Student student2 = new Student(
            "Khyati",
            20,
            new Address("1235"),
            Arrays.asList(new MobileNumber("1111"), new MobileNumber("3333"), new MobileNumber("1233")));

        Student student3 = new Student(
            "Jason",
            20,
            new Address("1236"),
            Arrays.asList(new MobileNumber("3333"), new MobileNumber("4444")));

        List<Student> students = Arrays.asList(student1, student2, student3);

        /*****************************************************
         Get student with exact match name "jayesh"
        *****************************************************/
        Optional<Student> stud = students.stream()
            .filter(student -> student.getName().equals("Jayesh"))
            .findFirst();
        System.out.println(stud.isPresent() ? stud.get().getName() : "No student found");
        System.out.println("--------------------");

        /*****************************************************
         Get student with matching address "1235"
        *****************************************************/
        Optional<Student> stud1 = students.stream()
            .filter(student -> student.getAddress().getZipcode().equals("1235"))
            .findFirst();
        System.out.println(stud1.isPresent() ? stud1.get().getName() : "No student found");
        System.out.println("--------------------");

        /*****************************************************
         Get all student having mobile numbers 3333.
        *****************************************************/
        List<Student> stud2 = students.stream()
            .filter(student111 -> student111.getMobileNumbers().stream().anyMatch(x -> Objects.equals(x.getNumber(), "3333")))
            .collect(Collectors.toList());

          String result1 = stud2.stream().map(std -> std.getName()).collect(Collectors.joining(",", "[", "]"));
          System.out.println(result1);
        System.out.println("--------------------");

        /*****************************************************
         Get all student having mobile number 1233 and 1234
         *****************************************************/
        List<Student> stud3 = students.stream()
            .filter(student -> student.getMobileNumbers().stream().allMatch(x -> Objects.equals(x.getNumber(), "1233") || Objects.equals(x.getNumber(), "1234")))
            .collect(Collectors.toList());

        String result4 = stud3.stream().map(std -> std.getName()).collect(Collectors.joining(",", "[", "]"));
        System.out.println(result4);
        System.out.println("--------------------");

        /*****************************************************
         Create a List<Student> from the List<TempStudent>
        *****************************************************/
        TempStudent tmpStud1 = new TempStudent(
            "Jayesh1",
            201,
            new Address("12341"),
            Arrays.asList(new MobileNumber("12331"), new MobileNumber("12341")));

        TempStudent tmpStud2 = new TempStudent(
            "Khyati1",
            202,
            new Address("12351"),
            Arrays.asList(new MobileNumber("11111"), new MobileNumber("33331"), new MobileNumber("12331")));

        List<TempStudent> tmpStudents = Arrays.asList(tmpStud1, tmpStud2);

        List<Student> studentList = tmpStudents.stream()
            .map(tmpStud -> new Student(tmpStud.name, tmpStud.age, tmpStud.address, tmpStud.mobileNumbers))
            .collect(Collectors.toList());

        System.out.println(studentList);
        System.out.println("--------------------");

        /*****************************************************
         Convert List<Student> to List<String> of student name
        *****************************************************/
        List<String> studentsName = studentList.stream()
            .map(Student::getName)
            .collect(Collectors.toList());

        System.out.println(studentsName.stream().collect(Collectors.joining(",")));
        System.out.println(studentsName.stream().collect(Collectors.joining(",", "[", "]")));
        System.out.println("--------------------");

        /*****************************************************
         Convert List<students> to String
        *****************************************************/
        String name = students.stream()
            .map(Student::getName)
            .collect(Collectors.joining(",", "[", "]"));
        System.out.println(name);
        System.out.println("--------------------");

        /*****************************************************
         Change the case of List<String>
        *****************************************************/
        List<String> nameList =
            Arrays.asList("Jayesh", "Dany", "Khyati", "Hello", "Mango");

        nameList.stream()
            .map(String::toUpperCase)
            .forEach(System.out::println);
        System.out.println("--------------------");

        /*****************************************************
         Sort List<String>
         *****************************************************/
        List<String> namesList =
            Arrays.asList("Jayesh", "Dany", "Khyati", "Hello", "Mango");

        namesList.stream()
            .sorted()
            .forEach(System.out::println);
        System.out.println("--------------------");

        /*****************************************************
         Conditionally apply Filter condition, say if flag is enabled then
         *****************************************************/
        boolean sortConditionFlag = true;

        Stream<Student> conditionalFilterResult = students.stream()
            .filter(std -> std.getName().startsWith("J"));

        if(sortConditionFlag){
            conditionalFilterResult = conditionalFilterResult.sorted(Comparator.comparing(Student::getName));
        }

        System.out.println("Before sorting :");
        students.forEach(s -> System.out.println(s.getName()));

        List<Student> list = conditionalFilterResult.collect(Collectors.toList());
        System.out.println("After filter and conditional sorting :");
        list.forEach(s -> System.out.println(s.getName()));

    }
}

Output

Jayesh
--------------------
Khyati
--------------------
[Khyati,Jason]
--------------------
[Jayesh]
--------------------
[Student{name='Jayesh1', age=201, address=com.javabypatel.sea.Address@685cb137, mobileNumbers=[com.javabypatel.sea.MobileNumber@6a41eaa2, com.javabypatel.sea.MobileNumber@7cd62f43]},

Student{name='Khyati1', age=202, address=com.javabypatel.sea.Address@6d4b1c02, mobileNumbers=[com.javabypatel.sea.MobileNumber@6093dd95, com.javabypatel.sea.MobileNumber@5622fdf, com.javabypatel.sea.MobileNumber@4883b407]}]
--------------------
Jayesh1,Khyati1
[Jayesh1,Khyati1]
--------------------
[Jayesh,Khyati,Jason]
--------------------
JAYESH
DANY
KHYATI
HELLO
MANGO
--------------------
Dany
Hello
Jayesh
Khyati
Mango
--------------------
Before sorting :
Jayesh
Khyati
Jason
After filter and conditional sorting :
Jason
Jayesh

You may also like to see


When to use Interface in java with example

Interface Vs Abstract class in Java OOPS.

Top Java Interface Interview Questions and Answers

When to use interface and abstract class in Java? what is the difference between them?

Java Multithreading and Concurrency Interview Questions and Answers with Example

Advanced Multithreading Interview Questions In Java

How ConcurrentHashMap works and ConcurrentHashMap interview questions.

Enjoy !!!! 
If you find any issue in post or face any error while implementing, Please comment.

Trigger Quartz Job Immediately.

Quartz Trigger Job Immediately In Java.


In this post, we will focus on how to fire the Quartz job immediately.


Skyline Problem in Java

Skyline Problem In Java.


A city's skyline is the outer contour of the silhouette formed by all the buildings in that city when viewed from a distance. 
Now suppose you are given the locations and height of all the buildings as shown on a cityscape below. Write a program to output the skyline formed by these buildings collectively.

Lets simplify the problem statement and understand it correctly,
If there are many buildings in a area as shown in below picture, If same buildings is viewed from distance then what we can see is not all the buildings but the skyline that is borders of all buildings.

You can see skyline of buildings if viewed from a side and remove all sections that are not visible/overlapped.
All buildings have common base and every building is represented by 3 points(left, right, height)

‘left': is x coordinate of building left wall.

‘right': is x coordinate of building right wall
‘height': is height of building.
A skyline is a collection of rectangular strips. A rectangular strip is represented as a pair (left, height) where left is x coordinate of building left wall and height is height of building.

Lets understand what is the input and the expected output.

INPUT:
You are given a building coordinates as shown below,

int[][] skyscraper = { {2,9,10},  {3,6,15},  {5,12,12},  {13,16,10}, {15,17,5} };

OUTPUT:
Skyline Coordinates = { {2,10},  {3,15}, {6,12}, {12,0}, {13,10}, {16,5}, {17,0} }


Pass parameters to Quartz Job Scheduler

How to pass parameter to Quartz Scheduler Cron Trigger example in Java.


Integration of Quartz scheduler with Spring boot. Java Quartz scheduler cron expression example. Spring quartz scheduler postgresql database example.

Quartz Scheduler:  
  1. Quartz is a richly featured, open source Job scheduling library. 
  2. Quartz can be used to create simple or complex schedules for executing multiple jobs. 
  3. Using quartz library, job can be schedule which can be executed instantly or to be executed later point of time. 
  4. Quartz also accepts cron expression using which complex jobs can be scheduled like
    "Run job after every 5 minutes" or "Run job every week on monday at 3 PM" etc.
Spring boot:
  1. Spring boot is (Spring + Configuration) bundle which helps you to develop application faster.
  2. Spring boot take care of many configurations and helps developer focus on business. 
  3. It includes an embedded tomcat (or jetty) server.

Download file in Angular2

Download file using Angular2.

Download file in Angular2 from server.

In this post, we will see how to download binary file from server using AngularJS and HTTP protocol.
 
Download binary file in angularjs using http
Download binary file in angularjs using HTTP

Many a times we need to download file from server via HTTP call, In this post we will see how to download file in Angular2 using GET/POST request from server.

Example demonstrates downloading binary file using Angular2 and REST service.