C
C#16mo ago
moshimoshi

✅ Finding node in binary search tree

Hi can someone help me understand the syntax of this code - I am struggling with understanding why we need to define the instance of current node in the iterative method but dont need to do so in the recursive method. Thanks! 🙂
//Recursive
public Node? Find(int key) {
// Base Case: Current node is null
if (this == null)
return null;

// Base Case: Current node is the key
if (this == key)
return this;

if (this < key) {
return this.right.Find(key);
}

else return this.left.Find(key);
}

//Iterative
public Node? Find(int key)
{
Node current = this;

while (current != null) {

if (current == key) {
return current;
}

else if (current < key) {
return current.right;
}

else (current > key) {
return current.left;
}
}

return null;
}
//Recursive
public Node? Find(int key) {
// Base Case: Current node is null
if (this == null)
return null;

// Base Case: Current node is the key
if (this == key)
return this;

if (this < key) {
return this.right.Find(key);
}

else return this.left.Find(key);
}

//Iterative
public Node? Find(int key)
{
Node current = this;

while (current != null) {

if (current == key) {
return current;
}

else if (current < key) {
return current.right;
}

else (current > key) {
return current.left;
}
}

return null;
}
0 Replies
No replies yetBe the first to reply to this messageJoin