简体   繁体   中英

Binary tree search algorithm

I think there is something I am not understanding with an algorithm I'm working with. I have a binary tree where "*" is the root, "C" is on the left, "+" is on the right and + has "a" to the left and "b" to the right.

This is the algorithm:

Module Find_Value ( List, Root, Value ) { 
    If ( Root is NULL ){
        Return NULL;
    }Else{
        If ( List [ Root ] .data equals Value )
            Return Root;
        Temp = Find_Value ( List, List[ Root ].left, Value )
        If ( Temp is NULL )
            Return Find_Value ( List, List[ Root ].right, Value );
        Else
            Return Temp;
    }
}

And I'm supposed to carry out Find_Value(List, 0, b)

I could be just reading it wrong, but I do not see any instruction to go back up the tree. I get find_value(List,1,C) the first run-through and then I see temp as looking to the left of C (which is null) and the the right of C (also null). Can anyone tell me I am just interpreting the instructions incorrectly?

This is what is happening here:

(I have replaced * with 0,C with 2 for better understanding and also used them as identifiers for each temp at each step)

1) Temp(*) = Find_Value ( List, *.left, b );

2) Temp(C) = Find_value ( List,C.left,b); //returns null , therefore Temp(C) = NULL;

3) If ( Temp(C) is NULL ) Return Find_Value ( List, C.right, Value ); //returns null;

4) therefore the 1st step returns null; Temp(*) = null;

5) If ( Temp(*) is NULL ) Return Find_Value ( List, *.right, Value );

6) Temp(+) = Find_Value ( List, +.left, Value );

7) Temp(a) = Find_Value ( List, a.left, Value ); // returns null

8) If ( Temp(a) is NULL ) Return Find_Value ( List, a.right, Value ); //returns null therefore Temp(+) = NULL;

9) If ( Temp(+) is NULL ) Return Find_Value ( List, +.right, Value );

10) If ( List [ Root ].data equals Value ) Return Root; where List[Root].data = b;

Step 9 returns b,followed by Step 5 returning b; and overall the function return b;

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM