Jordan Ranen
Jordan Ranen

Reputation: 25

search in whole binary search tree

I have a method which prints the title of the movie if it matches the year from the parameter.

private void searchByYear(BTNode root, int year) {
    BTNode temp = root;
    if(temp == null)
        return;
    else if(temp.data.titleYear == year){
        System.out.println(temp.data.title);
    }
    else{
        searchByYear(temp.left, year);
        searchByYear(temp.right, year);
    }
}

Problem: It prints some movies, not all. I believe the problme should be in the recursive call.

Note: The sorting is not on the basis of year, so I have to search from the whole tree. Also I want the method to print, not to return node.

Upvotes: 0

Views: 34

Answers (1)

Thiyagu
Thiyagu

Reputation: 17920

Merge the else if block with the else block so that it makes the recursive call after performing the check.

private void searchByYear(BTNode root, int year) {
    BTNode temp = root;
    if(temp == null)
        return;
    if(temp.data.titleYear == year){
        System.out.println(temp.data.title);
    }

    searchByYear(temp.left, year);
    searchByYear(temp.right, year);
 }

Upvotes: 2

Related Questions