class Node
{
public int key;
public Object data;
public Node left;
public Node right;
}
Node* search(Node root, int key)
{
if (root == null)
return null;
else if (key == root->key)
return root->data;
else if (key < root->key)
return searchTree(root->left, key);
else
return searchTree(root->right, key);
}
Rewrite this function iteratively instead of recursion
Requirements :
No global decelerations
Test run in main
class Object;
class Node
{
public:
int key;
Object* data;
Node* left;
Node* right;
};
Object* search(Node* root, int key)
{
while (root != nullptr) {
if (key == root->key) {
return root->data;
}
if (key < root->key) {
root = root->left;
}
else {
root = root->right;
}
}
return nullptr;
}
Comments
Leave a comment