package main
import "fmt"
// Node represents a tree node
type Node struct {
value int
left *Node
right *Node
}
// SearchTree searches for target in the binary search tree
func SearchTree(root *Node, target int) bool {
if root == nil {
return false // base case: empty tree
}
if root.value == target {
return true // found target
}
if target < root.value {
return SearchTree(root.left, target) // search left subtree
} else {
return SearchTree(root.right, target) // search right subtree
}
}
func main() {
// Build tree:
// 3
// / \
// 1 5
// / \
// 4 6
root := &Node{value: 3}
root.left = &Node{value: 1}
root.right = &Node{value: 5}
root.right.left = &Node{value: 4}
root.right.right = &Node{value: 6}
// Search for 6
found := SearchTree(root, 6)
fmt.Printf("Found 6 in tree: %v\n", found)
// Simulate array search
arr := []int{1, 2, 3, 4, 5}
foundArr := false
for _, v := range arr {
if v == 6 {
foundArr = true
break
}
}
fmt.Printf("Found 6 in array: %v\n", foundArr)
// Simulate linked list search
type ListNode struct {
val int
next *ListNode
}
head := &ListNode{val: 1}
head.next = &ListNode{val: 2}
head.next.next = &ListNode{val: 3}
head.next.next.next = &ListNode{val: 4}
head.next.next.next.next = &ListNode{val: 5}
curr := head
foundList := false
for curr != nil {
if curr.val == 6 {
foundList = true
break
}
curr = curr.next
}
fmt.Printf("Found 6 in linked list: %v\n", foundList)
}
if root == nil {
return false // base case: empty tree
}
stop search if tree node is empty
if root.value == target {
return true // found target
}
check if current node matches target
if target < root.value {
return SearchTree(root.left, target) // search left subtree
} else {
return SearchTree(root.right, target) // search right subtree
}
choose left or right branch based on target value
for _, v := range arr {
if v == 6 {
foundArr = true
break
}
}
linear scan through array to find target
for curr != nil {
if curr.val == 6 {
foundList = true
break
}
curr = curr.next
}
linear traversal through linked list nodes
Found 6 in tree: true
Found 6 in array: false
Found 6 in linked list: false