package main
import "fmt"
// Node represents a node in a binary tree
type Node struct {
val int
left *Node
right *Node
}
// SearchPlain searches for a value in a plain binary tree (no order)
func SearchPlain(root *Node, target int) bool {
if root == nil {
return false
}
if root.val == target {
return true
}
// Search left subtree
if SearchPlain(root.left, target) {
return true
}
// Search right subtree
return SearchPlain(root.right, target)
}
// SearchBST searches for a value in a BST using order
func SearchBST(root *Node, target int) bool {
if root == nil {
return false
}
if root.val == target {
return true
}
if target < root.val {
return SearchBST(root.left, target) // go left if smaller
} else {
return SearchBST(root.right, target) // go right if bigger or equal
}
}
func main() {
// Plain binary tree
plain := &Node{5, nil, nil}
plain.left = &Node{3, nil, nil}
plain.right = &Node{8, nil, nil}
plain.left.left = &Node{7, nil, nil}
plain.left.left.left = &Node{2, nil, nil}
plain.right.right = &Node{9, nil, nil}
// BST
bst := &Node{5, nil, nil}
bst.left = &Node{3, nil, nil}
bst.right = &Node{8, nil, nil}
bst.left.left = &Node{2, nil, nil}
bst.right.right = &Node{9, nil, nil}
fmt.Println("Search 2 in plain binary tree:", SearchPlain(plain, 2))
fmt.Println("Search 2 in BST:", SearchBST(bst, 2))
}
if root == nil { return false }
stop search if reached empty node
if root.val == target { return true }
found target value
if SearchPlain(root.left, target) { return true } ; return SearchPlain(root.right, target)
search left then right subtrees in plain tree (no order, checks both if needed)
if target < root.val { return SearchBST(root.left, target) } else { return SearchBST(root.right, target) }
use BST order to decide which subtree to search (skips half)
Search 2 in plain binary tree: true
Search 2 in BST: true