Binary Search Tree Recursion

195 Views Asked by At

Given the root node of a Binary Search Tree, I'm trying to create a recursive search where all nodes within a given maximum and minimum range are found but in the LEAST amount of visits.

So essentially the set up to this question will be(I think):

public Node finder(Node root, int max, int min) {};

1

There are 1 best solutions below

0
On

Create a function "check" which is recursively defined as

    check(Node x){
    if(x.right.elm()>min&&x.right.elm()<max){
        check(x.right); 
    }
    else if(x.right.elm()>max){
        check(x.right.left);    
    else if(x.right.elm()<min){
        check(x.right.right);
    }
    if(x.left.elm()>min&&x.left.elm()<max){
        check(x.left); 
    }
    else if(x.left.elm()>max){
        check(x.left.left);    
    else if(x.left.elm()<min){
        check(x.left.right);
    }
    }

Alternatively for a easier code you could create two functions check_right and check_left.