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.

GoData Integrity

Code

gosnippet
25 lines
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

FAQ

Any setup needed beyond the language runtime?
None — the language runtime is the only requirement. The file defines `Insert` at load time.