Skip to content

Commit

Permalink
feat: Replace recursion with iteration in BST.Contains()
Browse files Browse the repository at this point in the history
  • Loading branch information
idsulik committed Nov 8, 2024
1 parent 3faa2a0 commit c82ecd9
Showing 1 changed file with 10 additions and 9 deletions.
19 changes: 10 additions & 9 deletions bst/bst.go
Original file line number Diff line number Diff line change
Expand Up @@ -62,17 +62,18 @@ func (bst *BST[T]) Contains(value T) bool {
}

func (bst *BST[T]) contains(n *node[T], value T) bool {
if n == nil {
return false
}

if value < n.value {
return bst.contains(n.left, value)
} else if value > n.value {
return bst.contains(n.right, value)
cur := n
for cur != nil {
if value < cur.value {
cur = cur.left
} else if value > cur.value {
cur = cur.right
} else {
return true
}
}

return true
return false
}

// Remove deletes a value from the BST.
Expand Down

0 comments on commit c82ecd9

Please sign in to comment.