package main import "fmt" type Node struct { val int left *Node right *Node } func searchBST(root *Node, target int) *Node { if root == nil || root.val == target { return root } if target < root.val { return searchBST(root.left, target) } return searchBST(root.right, target) } func main() { root := &Node{val: 10} root.left = &Node{val: 5} root.right = &Node{val: 20} root.right.left = &Node{val: 15} result := searchBST(root, 15) if result != nil { fmt.Println(result.val) } else { fmt.Println("Not found") } }
The search starts at root (10). Since 15 > 10, it moves to right subtree (20). Since 15 < 20, it moves to left subtree of 20 (15). The code correctly finds 15.
package main import "fmt" type Node struct { val int left *Node right *Node } func searchBST(root *Node, target int) *Node { if root == nil || root.val == target { return root } if target < root.val { return searchBST(root.left, target) } return searchBST(root.right, target) } func main() { root := &Node{val: 10} root.left = &Node{val: 5} root.right = &Node{val: 20} root.right.left = &Node{val: 15} result := searchBST(root, 17) if result != nil { fmt.Println(result.val) } else { fmt.Println("Not found") } }
The search starts at root (10). Since 17 > 10, it moves to right subtree (20). Since 17 < 20, it moves to left subtree of 20 (15). Since 17 > 15, it moves to right subtree of 15, which is nil. So, the value 17 is not found in the BST.
BST property: left child values are less, right child values are greater. So search goes left if target is smaller, right if larger.
package main import "fmt" type Node struct { val int left *Node right *Node } func searchBST(root *Node, target int) *Node { if root == nil { return nil } if root.val == target { return root } if target > root.val { return searchBST(root.left, target) } return searchBST(root.right, target) } func main() { root := &Node{val: 10} root.left = &Node{val: 5} root.right = &Node{val: 20} result := searchBST(root, 5) if result != nil { fmt.Println(result.val) } else { fmt.Println("Not found") } }
The code incorrectly calls searchBST on root.left when target > root.val, which should be root.right. When searching for 5 (< 10), since the condition target > root.val is false, it takes the else branch and searches root.right instead of root.left, missing the node 5 and printing "Not found".
Search path: 10 (root) -> 5 (left child) -> 7 (right child of 5). Total nodes visited = 3.