简体   繁体   中英

What is happening in this function?

I was looking for a method to display the contents of Binary search tree in inorder method. I found this method which seems quite popular but I cannot understand how is this recursion working. How will the code ever reach cout? Also root node is being passed into the function when called by the main function. EDIT: This is considering that "root!=NULL".

    void display(struct tree *p)
{
    while(p!=NULL)
    {
        display(p->left);
        cout<<p->data;
        display(p->right);
    }
}

First of all, instead of while(p!=NULL) you should use if (p != null) . Otherwise, you get an infinite loop in case the root node is not null.

It first displays the left subtree calling recursively display(p->left) . After that it displays the node itself ( cout<data ) and finally the right subtree calling recursively display(p->right) .

Suppose you have the following tree:

      4
  2       6
1  3     5

A call to display(root), results in the following function calls:

display(4)
  display(2)
    display(1)
      display(null)
      cout 1
      display(null)
    cout 2
    display(3)
      display(null)
      cout 3
      display(null)
  cout 4
  display(6)
    display(5)
      display(null)
      cout 5
      display(null)
    cout 6
    display(null)

When the function is called for node "1", it first displays the left subtree by calling display(p->left) .
That function notices p==null returning therefore directly.
So control returns to display(1).
The next statement is cout << 1 .
After that, it displays the right subtree by calling display(p->right) .
That function notices p==null returning therefore directly.
So again, control returns to display(1).
At this point, display(1) has terminated and control returns to the function that called display(1), being display(2).
It finished its call to display(p->left) (being "1") and therefore executes it next statement, which is cout << 2 .

The reason that the code will reach cout is that function display will not recurse all the time.

Once the parameter passed to display become NULL ,that is,you have reached the leaf node of that tree, the recursion will start to trace back,the stack will start unwinding.Finally the control will return to the origin call of display .And it begins to execute the cout .

And that's why the judgement while(p!=NULL) is indispensable.

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