package main import "fmt" type Node struct { val int left *Node right *Node } func insert(root *Node, val int) *Node { if root == nil { return &Node{val: val} } if val < root.val { root.left = insert(root.left, val) } else { root.right = insert(root.right, val) } return root } func inorder(root *Node) { if root == nil { return } inorder(root.left) fmt.Print(root.val, " -> ") inorder(root.right) } func main() { var root *Node vals := []int{10, 5, 15, 3, 7} for _, v := range vals { root = insert(root, v) } inorder(root) fmt.Print("null\n") }
Inorder traversal of a BST visits nodes in ascending order because left subtree nodes are smaller, root is next, then right subtree nodes are larger.
Inserted values 10, 5, 15, 3, 7 create a BST where inorder traversal prints: 3 -> 5 -> 7 -> 10 -> 15 -> null.
The BST property ensures left children are smaller and right children are larger than the node, allowing the search to decide which subtree to explore next.
This halves the search space at each step, making search efficient like binary search.
func insert(root *Node, val int) *Node { if root == nil { return &Node{val: val} } if val <= root.val { root.left = insert(root.left, val) } else { root.right = insert(root.right, val) } return root } // Node struct is defined as usual.
The code allows duplicates by inserting them into the left subtree (val <= root.val).
This is valid and will not cause errors or infinite recursion.
package main import "fmt" type Node struct { val int left *Node right *Node } func insert(root *Node, val int) *Node { if root == nil { return &Node{val: val} } if val < root.val { root.left = insert(root.left, val) } else { root.right = insert(root.right, val) } return root } func minValueNode(node *Node) *Node { current := node for current.left != nil { current = current.left } return current } func deleteNode(root *Node, val int) *Node { if root == nil { return root } if val < root.val { root.left = deleteNode(root.left, val) } else if val > root.val { root.right = deleteNode(root.right, val) } else { if root.left == nil { return root.right } else if root.right == nil { return root.left } temp := minValueNode(root.right) root.val = temp.val root.right = deleteNode(root.right, temp.val) } return root } func inorder(root *Node) { if root == nil { return } inorder(root.left) fmt.Print(root.val, " -> ") inorder(root.right) } func main() { var root *Node vals := []int{20, 10, 30, 5, 15} for _, v := range vals { root = insert(root, v) } root = deleteNode(root, 10) inorder(root) fmt.Print("null\n") }
Node 10 has two children (5 and 15). Deleting it replaces 10 with 15 (smallest in right subtree).
Inorder traversal after deletion: 5 -> 15 -> 20 -> 30 -> null.
Without BST property, you cannot decide which subtree to explore, so you may need to check every node.
This makes search time linear, like scanning a list.