1

This algorithm correctly searches a tree and returns true if the searchValue is in the tree, I understand the base case, but I'm a little lost on the else statement, I'm not understanding what the || does in this scenario, is it returning both of those or just one in certain cases?

func search(node: Node?, searchValue: Int) -> Bool {

    if(node == nil){
        return false
    }
    if(node?.value == searchValue){
        return true
    } else {
        return search(node: node?.leftChild, searchValue: searchValue) || search(node: node?.rightChild, searchValue: searchValue)
    }
}
Andrew
  • 26,706
  • 9
  • 85
  • 101
tHatpart
  • 1,302
  • 3
  • 12
  • 27
  • 1
    It's a boolean OR that returns true if either half is true. In addition, it short circuits and avoids calling the second search if the first returns true. It is the equivalent of `if search(left) { return true } else { return search(right) }`. – vacawama Feb 06 '20 at 21:26
  • okay so it returns whichever one is true, if both are true it returns the first one? – tHatpart Feb 06 '20 at 22:28
  • It only returns true or false. It doesn't return anything else. So if it finds the searchValue in the left subtree, it is done and doesn't bother searching the right subtree. If the left returns true, it doesn't matter if the right is true or false. The OR will be true, so why check. – vacawama Feb 06 '20 at 22:31
  • BTW, there is never a case in a binary search tree that the searchValue would be found in both the left subtree and the right subtree. All values in the left tree are less than the value in the current node, and all values in the right tree are greater than the value in the current node. – vacawama Feb 06 '20 at 22:47

0 Answers0