I am not able to understand the recursion of functions. How it works? how the values are stored and all?

后端 未结 4 1012
名媛妹妹
名媛妹妹 2021-01-28 04:19

I am not able to understand the recursion of functions. How it works? how the values are stored and all?

int tree_size(struct node* node) { 
  if (node==NULL) {         


        
4条回答
  •  星月不相逢
    2021-01-28 04:59

    I think the line that is confusing you most is..

    return(tree_size(node->left) + tree_size(node->right) + 1);
    

    If you called this function on the top node, it will tell you that the number of nodes in the tree is the number of nodes to the left, plus the number to the right, plus this on node you just called the function on.

    Now, I don't think it's the recursion that is confusing you, if it is, leave a comment and I can explain that a bit more.

    The problem I think you are having is what order the line will be executed. Well, it follows the logical maths rules for 'addition'. Note, we know we do not have to get concerned with operator overloads, as tree_size is returning an int, so we have

    intA + intB + intC;
    

    I trust I do not need to tell you that it does not matter what order you add these three values, you will get the same result.

    however, the order that these are added is well defined. If you think of the + operator as it's function, it will be a bit clearer. We basically have (and I hope I get this right):

    operator+(intA , operator+( intB, intC);
    

    so, you can see, we need to first calculate B + C before we can add on A, or if we take this back to the line of code in question, we get the tree_size on the right first, add one to it, then add on the tree_size of the left. This is an important thing to be aware of, you could do something very strange, such as edit the tree size when you get the value... say, if you moved nodes from one side to the other. Of course, it would be a very bad tree if getting the size of it was not something you can rely on.

    I fear I might have gone on a bit too much here, so if I have missed the mark a bit, just leave a comment and I will gladly try to help improve this answer for you.

提交回复
热议问题