简体   繁体   中英

Binary Search Tree Successor Function

Im working on a binary search tree program and I am trying to find the successor of a node given its data. I am following psuedocode and feel like I am doing it correctly, but clearly I am not because it is not working.

Here is what I have:

ZipInfo * BinarySearchTree::treeSuccessor(string city, string state)
{

 ZipInfo *successor = new ZipInfo(city, state);

 ZipInfo *y = successor->getRight();
 ZipInfo *yx = new ZipInfo();
 if(successor->getRight() != NULL)
 {
     while(y->getLeft() != NULL)
     {
         y = y->getLeft();
     }
     return y;
 }

 else
 {
     yx = successor->getParent();
     while((yx != NULL) && (successor == yx->getRight()))
     {
         successor = yx;
         yx = yx->getParent();

     }
     return yx;
 }


}

Each node holds data which are city and state. So if the user enters Phoenix and Arizona as the city and state, the function should find this node's successor in the BST.

The code seems to expect that the line:

ZipInfo *successor = new ZipInfo(city, state);

will find the pointer to the node with data matching city and state data. This won't happen, as it will return the pointer to a newly created node. You'll need to first find the existing node that actually matches the data (if such a node even exists). Then you traverse the tree starting with that node.

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