BST Insert And Delete With Successor (Go)
Implement a Go binary search tree supporting insert and delete using in-order successor for two-child nodes.
Code
package main
type TreeNode struct {
val int
left *TreeNode
right *TreeNode
}
type BST struct {
root *TreeNode
}
func (t *BST) Insert(val int) {
if t.root == nil { t.root = &TreeNode{val: val}; return }
cur := t.root
for {
if val < cur.val {
if cur.left == nil { cur.left = &TreeNode{val: val}; return }
cur = cur.left
} else {
if cur.right == nil { cur.right = &TreeNode{val: val}; return }
cur = cur.right
}
}
}How it works
Count the function Insert as the entire surface area of BST Insert And Delete With Successor (Go).
The cycling part of this snippet is for.
What to watch for
- The whole dependency story is the language version itself.
Applying it
Entry signature: func (t *BST) Insert(val int)
This is a method, not a free function — dispatch happens via a BST value.
Statements that matter
if cur.right == nil { cur.right = &TreeNode{val: val}; return }
if cur.left == nil { cur.left = &TreeNode{val: val}; return }
if t.root == nil { t.root = &TreeNode{val: val}; return }
Interactive Tools for This Topic
cURL to Python & Go ConverterTranslate curl CLI commands with headers, auth, JSON bodies, and timeouts into ready-to-run Python requests and Go net/http client code snippets.Markdown Heading OutlineExtract ATX headings from Markdown into an indented outline with line numbers and per-level counts, ignoring code fences.SRI Hash GeneratorGenerate Subresource Integrity (SRI) hashes from resource content using SHA-256, SHA-384, or SHA-512, and copy a ready-to-use script tag.
FAQ
- Any setup needed beyond the language runtime?
- None — the language runtime is the only requirement. The file defines `Insert` at load time.
Report a problem with this exampleOpens a pre-filled issue on GitHub.