简体   繁体   中英

Binary Search tree Inorder tree display

I am using two pointers in BST root and top. top pointer moves along the tree for insertion and display. Now my Question is that in my inorder code. i move the top pointer down the tree till the time NULL is found through recursion as follows

void display()
{

    if(top->left!=NULL)
    {
      top=top->left;
      display();
    }

    cout<<"\n\nnow the address of top is "<<top;
    return;
}

elements in the tree are for the time being 12 11 and 10; now in the last recursive call of the fuction, top pointer moves at 10 but how to move the top pointer back after the last function i mean ; in every cout the adress of top is of 10 means that the pointer remains at 10 even if the control comes back to a previous recursive function. there are two recursive functions in this code, display is called tWo times, after the second display function the top pointer doesnt move up the tree rather it remains on 10, i want to move the top pointer back after the completion of every recursive display function. help. BUT WITHOUT INVOLVING ARGUMENTS IN DISPLAY FUNCTION.

In this sample, your code appears to be stepping down the left side of each tree (but ignoring the right side).

if(top->left!=NULL)
{
  top=top->left;
  display();
}

Generally, a BST has nodes, each node has data, a ptr to left child, and a ptr to right child.

And it appears that your nodes do not yet contain a "display()" method.


In a tree, I suspect you want to be invoking

<a node> -> display();

To avoid passing pointers in your recursive 'display' calls.

Next, your names are misleading (to me). So perhaps if you rename some things, the following might be appropriate and more understandable to you.

Each node needs at least 3 parts, and the display method. For a depth-first-search, in-line display maybe the following will trigger some thoughts.

Node::display(void)
{
   // first, display nodes of left side-of-tree
   if(nullptr != left)
   { 
       left->display();
   }
   // else no left node available


   // for in-order, cout the data at this node
   std::cout << data << std::endl;


   // continue the depth-first display by tracing the right side
   if (nullptr != right)
   {
       right->display();
   }
}

To begin the the display track, you need to have an anchor of the tree. Perhaps something like:

Tree::display()
{
   if(tree.Top) // is tree not empty?
      tree.Top->display();
   ...

So ... I am suggesting a class for tree, another class for node, a display method for tree, a display method for node, etc.

Hope this helps ... Good luck.

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