Go tree programs teach you how to store data in a branching shape, where each item can have children below it. In this post, you will write fourteen programs with their exact output and the logic explained in comments, covering a binary search tree, the four traversals, height, delete, validate, lowest common ancestor and invert.
You should first finish our Go recursion programs, because almost every tree function calls itself. The Go linked list programs and Go stack and queue programs are useful too, since a tree node is a list node with two pointers. All programs were tested on Go 1.27.
What are Go Tree Programs?
Go tree programs build nodes that point to child nodes. In a binary tree, each node has at most two children, called Left and Right. The top node is the root, and nodes with no children are called leaves.
Think of a family tree drawn upside down. The grandparent sits at the top, their children sit below, and the grandchildren sit below them. Each person links only to their own children.
Why Go Tree Programs Matter
Trees appear wherever data has a natural “inside of” or “sorted” shape.
- Fast search: a balanced binary search tree finds a value in O(log n) steps.
- Real data: folders, HTML pages, JSON and company org charts are all trees.
- Databases: indexes use B-trees, a wider cousin of the binary search tree.
- Interviews: traversals, height, validate BST and lowest common ancestor are very common.
How Go Tree Programs Work
Most Go tree programs in this post use a binary search tree (BST). The rule is simple: every value in the left subtree is smaller than the node, and every value in the right subtree is bigger. So to search, you go left for smaller values and right for bigger ones.

We build the same tree in most programs by inserting 50, 30, 70, 20, 40, 60 and 80. The table below shows the four traversal orders for that tree.
| Traversal | Order rule | Output |
|---|---|---|
| Inorder | Left, node, right | 20 30 40 50 60 70 80 |
| Preorder | Node, left, right | 50 30 20 40 70 60 80 |
| Postorder | Left, right, node | 20 40 30 60 80 70 50 |
| Level order | Row by row, left to right | 50 30 70 20 40 60 80 |
Basic Go Tree Programs
These first Go tree programs make a tiny tree by hand, then build a BST and walk it in each of the four orders.
Program 1: Make a Tiny Tree by Hand
package main
import "fmt"
// Node is one box in the tree. It holds a value and links to two children.
type Node struct {
Val int // the number stored in this node
Left *Node // pointer to the left child (nil means "no child")
Right *Node // pointer to the right child
}
func main() {
// Step 1: make three separate nodes.
// := creates a new variable, and & gives us a pointer to the new node.
root := &Node{Val: 50}
leftChild := &Node{Val: 30}
rightChild := &Node{Val: 70}
// Step 2: link the two children to the root
root.Left = leftChild
root.Right = rightChild
// Step 3: reach each child through the root
fmt.Println("root:", root.Val)
fmt.Println("left child:", root.Left.Val)
fmt.Println("right child:", root.Right.Val)
// A leaf has no children, so both of its links are nil (empty)
isLeaf := leftChild.Left == nil && leftChild.Right == nil
fmt.Println("30 is a leaf:", isLeaf)
}
root: 50
left child: 30
right child: 70
30 is a leaf: true
This is the smallest possible tree. First you create three nodes, then you set the root’s Left and Right links. After that, root.Left.Val follows the link from the root down to its child. The node 30 has no links of its own, so it is a leaf.
Program 2: Build a BST and Print It Inorder
package main
import "fmt"
// Node is one item in the tree with links to its two children.
type Node struct {
Val int
Left, Right *Node // two pointers of the same type on one line
}
// insert puts value in the right place and returns the root of the tree.
func insert(root *Node, value int) *Node {
if root == nil {
return &Node{Val: value} // empty spot found: create the node here
}
if value < root.Val {
root.Left = insert(root.Left, value) // smaller values go left
} else {
root.Right = insert(root.Right, value) // bigger or equal go right
}
return root
}
// inorder visits left, then the node, then right.
// For a BST, this prints the values in sorted order.
func inorder(node *Node) {
if node == nil {
return // nothing here, so go back up
}
inorder(node.Left)
fmt.Print(node.Val, " ")
inorder(node.Right)
}
func main() {
var root *Node // an empty tree starts as nil
// range gives each value of the slice, one by one
for _, value := range []int{50, 30, 70, 20, 40, 60, 80} {
root = insert(root, value)
}
inorder(root)
fmt.Println()
}
20 30 40 50 60 70 80
The insert function walks down from the root, going left for smaller values and right for bigger ones. When it reaches an empty spot, it creates the new node there. Inorder traversal of a BST always gives sorted output, which is a handy check in Go tree programs. That is a quick way to test that your insert works.
Program 3: Preorder and Postorder Traversal
package main
import "fmt"
// Node is one item in the tree with links to its two children.
type Node struct {
Val int
Left, Right *Node
}
// insert adds value in the right place (same as Program 2).
func insert(root *Node, value int) *Node {
if root == nil {
return &Node{Val: value}
}
if value < root.Val {
root.Left = insert(root.Left, value)
} else {
root.Right = insert(root.Right, value)
}
return root
}
// preorder visits the node first. Useful to copy or print a tree top-down.
func preorder(node *Node, result *[]int) {
if node == nil {
return
}
*result = append(*result, node.Val) // *result means "the slice the pointer points to"
preorder(node.Left, result)
preorder(node.Right, result)
}
// postorder visits the children first. Useful to delete a tree or sum folder sizes.
func postorder(node *Node, result *[]int) {
if node == nil {
return
}
postorder(node.Left, result)
postorder(node.Right, result)
*result = append(*result, node.Val) // the node comes last
}
func main() {
var root *Node
for _, value := range []int{50, 30, 70, 20, 40, 60, 80} {
root = insert(root, value)
}
var preList, postList []int
preorder(root, &preList) // &preList passes a pointer, so the function can grow it
postorder(root, &postList)
fmt.Println("pre: ", preList)
fmt.Println("post:", postList)
}
pre: [50 30 20 40 70 60 80]
post: [20 40 30 60 80 70 50]
We pass a pointer to the result slice, so every recursive call appends to the same slice. In preorder, the node is added before its children. In postorder, it is added after them. The only difference between the three orders is where the “visit” line sits.
Program 4: Level Order Traversal with a Queue
package main
import "fmt"
// Node is one item in the tree with links to its two children.
type Node struct {
Val int
Left, Right *Node
}
// insert adds value in the right place (same as Program 2).
func insert(root *Node, value int) *Node {
if root == nil {
return &Node{Val: value}
}
if value < root.Val {
root.Left = insert(root.Left, value)
} else {
root.Right = insert(root.Right, value)
}
return root
}
// levels returns one slice per row of the tree, from top to bottom.
func levels(root *Node) [][]int {
var result [][]int
if root == nil {
return result
}
queue := []*Node{root} // a slice used as a queue: add at the back, take from the front
for len(queue) > 0 {
size := len(queue) // number of nodes in this row
var row []int
for i := 0; i < size; i++ {
// Step 1: take the first node out of the queue
current := queue[0]
queue = queue[1:] // [1:] keeps everything except the first item
row = append(row, current.Val)
// Step 2: its children join the queue for the next row
if current.Left != nil {
queue = append(queue, current.Left)
}
if current.Right != nil {
queue = append(queue, current.Right)
}
}
result = append(result, row)
}
return result
}
func main() {
var root *Node
for _, value := range []int{50, 30, 70, 20, 40, 60, 80} {
root = insert(root, value)
}
fmt.Println(levels(root))
}
[[50] [30 70] [20 40 60 80]]
The queue starts with only the root. Each time you take a node out, you add its children to the back of the queue. Reading size before the inner loop lets us split the output into rows. Questions like “right side view” and “zigzag order” reuse this exact pattern.

BST Go Tree Programs
These Go tree programs use the BST rule to place values, search, find limits and delete nodes.
Program 5: Watch Where Each Value Goes in a BST
package main
import "fmt"
// Node is one item in the tree with links to its two children.
type Node struct {
Val int
Left, Right *Node
}
// insertAndShow adds value to the tree and prints every turn it takes.
func insertAndShow(root *Node, value int) *Node {
if root == nil {
fmt.Printf(" placed %d here\n", value) // %d prints a whole number
return &Node{Val: value}
}
if value < root.Val {
fmt.Printf(" %d < %d, go left\n", value, root.Val)
root.Left = insertAndShow(root.Left, value)
} else {
fmt.Printf(" %d >= %d, go right\n", value, root.Val)
root.Right = insertAndShow(root.Right, value)
}
return root
}
func main() {
var root *Node
for _, value := range []int{50, 30, 70, 40} {
fmt.Println("insert", value)
root = insertAndShow(root, value)
}
}
insert 50
placed 50 here
insert 30
30 < 50, go left
placed 30 here
insert 70
70 >= 50, go right
placed 70 here
insert 40
40 < 50, go left
40 >= 30, go right
placed 40 here
This is the same insert as before, with a print line at every turn. The first value becomes the root because the tree is empty. Each later value compares itself with the nodes on its way down. For 40, it goes left of 50 and then right of 30.
Program 6: Search a BST
package main
import "fmt"
// Node is one item in the tree with links to its two children.
type Node struct {
Val int
Left, Right *Node
}
// insert adds value in the right place (same as Program 2).
func insert(root *Node, value int) *Node {
if root == nil {
return &Node{Val: value}
}
if value < root.Val {
root.Left = insert(root.Left, value)
} else {
root.Right = insert(root.Right, value)
}
return root
}
// search walks down without recursion and counts the steps.
// It returns two values: whether target was found, and the step count.
func search(root *Node, target int) (bool, int) {
steps := 0
current := root
for current != nil {
steps++
if target == current.Val {
return true, steps
} else if target < current.Val {
current = current.Left // the target can only be on the left
} else {
current = current.Right // the target can only be on the right
}
}
return false, steps // we fell off the tree, so it is not there
}
func main() {
var root *Node
for _, value := range []int{50, 30, 70, 20, 40, 60, 80} {
root = insert(root, value)
}
fmt.Println(search(root, 60))
fmt.Println(search(root, 45))
}
true 3
false 3
The loop starts at the root and compares the target with the current node. If the target is smaller, it moves left, otherwise it moves right. Each step throws away half of the remaining tree, so a tree of 7 nodes needs at most 3 steps. A balanced tree of one million nodes needs only about 20.
Program 7: Height, Node Count and Leaf Count
package main
import "fmt"
// Node is one item in the tree with links to its two children.
type Node struct {
Val int
Left, Right *Node
}
// insert adds value in the right place (same as Program 2).
func insert(root *Node, value int) *Node {
if root == nil {
return &Node{Val: value}
}
if value < root.Val {
root.Left = insert(root.Left, value)
} else {
root.Right = insert(root.Right, value)
}
return root
}
// height is 1 plus the taller of the two subtrees. An empty tree has height 0.
func height(node *Node) int {
if node == nil {
return 0
}
leftHeight := height(node.Left)
rightHeight := height(node.Right)
return 1 + max(leftHeight, rightHeight) // max returns the bigger number
}
// count returns how many nodes the tree has.
func count(node *Node) int {
if node == nil {
return 0
}
return 1 + count(node.Left) + count(node.Right)
}
// leaves returns how many nodes have no children.
func leaves(node *Node) int {
if node == nil {
return 0
}
if node.Left == nil && node.Right == nil {
return 1 // no children, so this is a leaf
}
return leaves(node.Left) + leaves(node.Right)
}
func main() {
var root *Node
for _, value := range []int{50, 30, 70, 20, 40, 60, 80, 10} {
root = insert(root, value)
}
fmt.Println("height:", height(root), "nodes:", count(root), "leaves:", leaves(root))
}
height: 4 nodes: 8 leaves: 4
Many Go tree programs share this shape, and all three functions here follow it. First you handle nil, then you combine the answers from the left and right children. The extra value 10 hangs below 20, so the height grows to 4. Once you see this pattern, most tree questions become short.
Program 8: Smallest and Largest Value in a BST
package main
import "fmt"
// Node is one item in the tree with links to its two children.
type Node struct {
Val int
Left, Right *Node
}
// insert adds value in the right place (same as Program 2).
func insert(root *Node, value int) *Node {
if root == nil {
return &Node{Val: value}
}
if value < root.Val {
root.Left = insert(root.Left, value)
} else {
root.Right = insert(root.Right, value)
}
return root
}
// minNode keeps going left. The leftmost node holds the smallest value.
func minNode(node *Node) *Node {
for node.Left != nil {
node = node.Left
}
return node
}
// maxNode keeps going right. The rightmost node holds the largest value.
func maxNode(node *Node) *Node {
for node.Right != nil {
node = node.Right
}
return node
}
func main() {
var root *Node
for _, value := range []int{50, 30, 70, 20, 40, 60, 80} {
root = insert(root, value)
}
fmt.Println(minNode(root).Val, maxNode(root).Val)
}
20 80
Each function follows one link again and again until there is no next node. No comparisons are needed. The BST rule already put the smallest value at the far left and the biggest at the far right.
Program 9: Delete a Node from a BST
package main
import "fmt"
// Node is one item in the tree with links to its two children.
type Node struct {
Val int
Left, Right *Node
}
// insert adds value in the right place (same as Program 2).
func insert(root *Node, value int) *Node {
if root == nil {
return &Node{Val: value}
}
if value < root.Val {
root.Left = insert(root.Left, value)
} else {
root.Right = insert(root.Right, value)
}
return root
}
// inorder prints the values in sorted order.
func inorder(node *Node) {
if node != nil {
inorder(node.Left)
fmt.Print(node.Val, " ")
inorder(node.Right)
}
}
// remove deletes value and returns the new root of this subtree.
func remove(node *Node, value int) *Node {
if node == nil {
return nil // value not found
}
if value < node.Val {
node.Left = remove(node.Left, value)
return node
}
if value > node.Val {
node.Right = remove(node.Right, value)
return node
}
// Step 1: we found the node. With 0 or 1 child, the child takes its place.
if node.Left == nil {
return node.Right
}
if node.Right == nil {
return node.Left
}
// Step 2: with 2 children, find the smallest value on the right side
successor := node.Right
for successor.Left != nil {
successor = successor.Left
}
// Step 3: copy that value here, then delete the old copy on the right
node.Val = successor.Val
node.Right = remove(node.Right, successor.Val)
return node
}
func main() {
var root *Node
for _, value := range []int{50, 30, 70, 20, 40, 60, 80} {
root = insert(root, value)
}
root = remove(root, 20) // a leaf
root = remove(root, 50) // the root, which has two children
inorder(root)
fmt.Println("| root:", root.Val)
}
30 40 60 70 80 | root: 60
Deleting 20 is easy because it is a leaf, so its parent simply gets nil. When the node has two children, its inorder successor (60) takes its value. The successor has no left child, so deleting it is an easy case.
Most Asked Interview Go Tree Programs
These Go tree programs are the ones interviewers ask most often.
Program 10: Check if a Tree is a Valid BST
package main
import (
"fmt"
"math"
)
// Node is one item in the tree with links to its two children.
type Node struct {
Val int
Left, Right *Node
}
// isValid checks that every value sits inside the allowed range (low, high).
func isValid(node *Node, low, high int) bool {
if node == nil {
return true // an empty tree breaks no rules
}
if node.Val <= low || node.Val >= high {
return false // value breaks a rule set by an ancestor
}
// left side must stay below node.Val, right side must stay above it
leftOK := isValid(node.Left, low, node.Val)
rightOK := isValid(node.Right, node.Val, high)
return leftOK && rightOK
}
func main() {
// &Node{50, left, right} fills Val, Left and Right in order
good := &Node{50, &Node{30, nil, nil}, &Node{70, nil, nil}}
// 60 is right of 30, but it is in the LEFT subtree of 50, so it is wrong
bad := &Node{50, &Node{30, nil, &Node{60, nil, nil}}, &Node{70, nil, nil}}
// math.MinInt and math.MaxInt are the smallest and largest int values
fmt.Println(isValid(good, math.MinInt, math.MaxInt))
fmt.Println(isValid(bad, math.MinInt, math.MaxInt))
}
true
false
The root may hold any value, so its range is the whole int range. When you go left, the node’s value becomes the new upper limit. When you go right, it becomes the new lower limit. Checking only a node against its own children is the classic mistake, and the bad tree passes that weak test.
Program 11: Lowest Common Ancestor in a BST
package main
import "fmt"
// Node is one item in the tree with links to its two children.
type Node struct {
Val int
Left, Right *Node
}
// insert adds value in the right place (same as Program 2).
func insert(root *Node, value int) *Node {
if root == nil {
return &Node{Val: value}
}
if value < root.Val {
root.Left = insert(root.Left, value)
} else {
root.Right = insert(root.Right, value)
}
return root
}
// lca walks down until first and second split to different sides.
func lca(root *Node, first, second int) *Node {
current := root
for current != nil {
if first < current.Val && second < current.Val {
current = current.Left // both are smaller, so go left
} else if first > current.Val && second > current.Val {
current = current.Right // both are bigger, so go right
} else {
return current // they split here, or one of them is this node
}
}
return nil
}
func main() {
var root *Node
for _, value := range []int{50, 30, 70, 20, 40, 60, 80} {
root = insert(root, value)
}
fmt.Println(lca(root, 20, 40).Val, lca(root, 20, 80).Val, lca(root, 60, 70).Val)
}
30 50 70
Both values start together at the root. While they are both smaller or both bigger, you move down on that side. The first node where the two values go different ways is the answer. In a plain binary tree without the BST rule, you would check both subtrees with recursion instead.
Program 12: Invert (Mirror) a Binary Tree
package main
import "fmt"
// Node is one item in the tree with links to its two children.
type Node struct {
Val int
Left, Right *Node
}
// invert swaps the left and right children of every node.
func invert(node *Node) *Node {
if node == nil {
return nil
}
// Step 1: mirror both subtrees first
newLeft := invert(node.Right)
newRight := invert(node.Left)
// Step 2: attach them on the opposite sides
node.Left = newLeft
node.Right = newRight
return node
}
// preorder prints the node, then its left side, then its right side.
func preorder(node *Node) {
if node != nil {
fmt.Print(node.Val, " ")
preorder(node.Left)
preorder(node.Right)
}
}
func main() {
root := &Node{4, &Node{2, &Node{1, nil, nil}, &Node{3, nil, nil}},
&Node{7, &Node{6, nil, nil}, &Node{9, nil, nil}}}
preorder(root)
fmt.Println()
preorder(invert(root))
fmt.Println()
}
4 2 1 3 7 6 9
4 7 9 6 2 3 1
The function first mirrors the right subtree and the left subtree. Then it puts the mirrored right side on the left and the mirrored left side on the right. The function visits each node once, so it is O(n).
Program 13: Check if a Tree is Balanced
package main
import "fmt"
// Node is one item in the tree with links to its two children.
type Node struct {
Val int
Left, Right *Node
}
// checkHeight returns the height, or -1 as soon as any subtree is unbalanced.
func checkHeight(node *Node) int {
if node == nil {
return 0
}
leftHeight := checkHeight(node.Left)
rightHeight := checkHeight(node.Right)
// Step 1: pass the -1 signal up if a subtree is already unbalanced
if leftHeight == -1 || rightHeight == -1 {
return -1
}
// Step 2: the two heights may differ by at most 1
if leftHeight-rightHeight > 1 || rightHeight-leftHeight > 1 {
return -1
}
return 1 + max(leftHeight, rightHeight)
}
func main() {
balanced := &Node{2, &Node{1, nil, nil}, &Node{3, nil, nil}}
chain := &Node{1, nil, &Node{2, nil, &Node{3, nil, nil}}} // like a linked list
fmt.Println(checkHeight(balanced) != -1, checkHeight(chain) != -1)
}
true false
Each node asks its two children for their heights. If the heights differ by more than 1, it returns -1, and every parent passes that -1 up. Returning -1 as a signal means we compute every height only once, so this is O(n). Calling height separately at every node would be O(n squared).
Program 14: Inorder Traversal Without Recursion
package main
import "fmt"
// Node is one item in the tree with links to its two children.
type Node struct {
Val int
Left, Right *Node
}
// inorderLoop uses a stack slice instead of recursive calls.
func inorderLoop(root *Node) []int {
var result []int
var stack []*Node
current := root
for current != nil || len(stack) > 0 {
// Step 1: go as far left as possible, saving each node on the stack
for current != nil {
stack = append(stack, current)
current = current.Left
}
// Step 2: take the last saved node off the stack and visit it
current = stack[len(stack)-1]
stack = stack[:len(stack)-1] // [:len-1] drops the last item
result = append(result, current.Val)
// Step 3: then handle its right subtree
current = current.Right
}
return result
}
func main() {
root := &Node{50, &Node{30, &Node{20, nil, nil}, &Node{40, nil, nil}},
&Node{70, &Node{60, nil, nil}, &Node{80, nil, nil}}}
fmt.Println(inorderLoop(root))
}
[20 30 40 50 60 70 80]
The stack remembers the nodes you passed on the way left. When you cannot go further left, you pop a node, print it and move to its right child. This avoids deep recursion on very tall trees. Interviewers often ask for it after you write the recursive version.
BST vs Slice in Go Tree Programs
A sorted slice also gives fast search with binary search, so when is a tree better? The table below compares them.
| Feature | Balanced BST | Sorted slice |
|---|---|---|
| Search | O(log n) | O(log n) |
| Insert | O(log n) | O(n), shifts items |
| Delete | O(log n) | O(n), shifts items |
| Memory | Two pointers per node | Values only |
| Worst case | O(n) if it becomes a chain | Always the same |
A simple rule helps: if data changes often, use a balanced tree. If you load data once and only search, a sorted slice is simpler and faster.
Common Mistakes in Go Tree Programs
- Forgetting the nil check: every recursive function must handle
node == nilfirst. - Not returning the root:
insertandremovemust return the node so parents can relink. - Validating only parent and child: use a range, as in Program 10.
- Inserting sorted data: 1, 2, 3, 4 turns a BST into a slow chain.
- Mixing up height and depth: height counts down to the leaves, depth counts up to the root.
Best Practices for Go Tree Programs
- Write the nil case first, then the rule for one node.
- Use level order with a queue for any “row by row” question.
- Return -1 or an ok flag to stop early, as in the balanced check.
- Use iteration for very deep trees to avoid huge call stacks.
- Draw a small tree of 5 to 7 nodes and trace your code by hand.
Go Tree Programs Interview Questions and Answers
These are the tree questions interviewers ask most, and they build on the Go tree programs above. Each code answer is complete, with real output from Go 1.27.
Concept Questions on Go Tree Programs
Q1. What is the difference between a binary tree and a binary search tree?
A binary tree only limits each node to two children. A binary search tree adds a rule: left values are smaller and right values are bigger, which makes search fast.
Q2. What is the height of a tree with one node?
It is 1 with the definition used in this post, where an empty tree has height 0. Some books count edges instead, which gives 0. Say which one you use in an interview.
Q3. Which traversal gives sorted output for a BST?
Inorder traversal: left, node, right. Preorder and postorder do not give sorted output.
Q4. What does this program print?
package main
import "fmt"
// Node is one item in the tree with links to its two children.
type Node struct {
Val int
Left, Right *Node
}
// sum adds up every value in the tree.
func sum(node *Node) int {
if node == nil {
return 0
}
return node.Val + sum(node.Left) + sum(node.Right) // node plus both subtrees
}
func main() {
root := &Node{10, &Node{5, nil, &Node{2, nil, nil}}, &Node{-3, nil, nil}}
fmt.Println(sum(root))
}
14
10 + 5 + 2 – 3 is 14. Every node is visited once.
Coding Questions
Q5. How do you find the kth smallest value in a BST?
package main
import "fmt"
// Node is one item in the tree with links to its two children.
type Node struct {
Val int
Left, Right *Node
}
// walk does an inorder visit and stops at the kth node.
// count and answer are pointers, so every call shares the same two numbers.
func walk(node *Node, k int, count *int, answer *int) {
if node == nil || *count >= k {
return
}
walk(node.Left, k, count, answer)
*count = *count + 1
if *count == k {
*answer = node.Val
return
}
walk(node.Right, k, count, answer)
}
// kthSmallest returns the kth smallest value, or -1 if the tree is too small.
func kthSmallest(root *Node, k int) int {
count := 0
answer := -1
walk(root, k, &count, &answer)
return answer
}
func main() {
root := &Node{50, &Node{30, &Node{20, nil, nil}, &Node{40, nil, nil}},
&Node{70, &Node{60, nil, nil}, &Node{80, nil, nil}}}
fmt.Println(kthSmallest(root, 3), kthSmallest(root, 6))
}
40 70
Inorder gives sorted order, so the kth visit is the kth smallest. The walk function adds 1 to count at each visit. When count reaches k, it saves the value in answer and stops.
Q6. How do you check if two trees are the same?
package main
import "fmt"
// Node is one item in the tree with links to its two children.
type Node struct {
Val int
Left, Right *Node
}
// sameTree reports whether two trees have the same shape and values.
func sameTree(first, second *Node) bool {
if first == nil || second == nil {
return first == second // both nil is true, only one nil is false
}
if first.Val != second.Val {
return false
}
return sameTree(first.Left, second.Left) && sameTree(first.Right, second.Right)
}
func main() {
treeA := &Node{1, &Node{2, nil, nil}, nil}
treeB := &Node{1, &Node{2, nil, nil}, nil}
treeC := &Node{1, nil, &Node{2, nil, nil}}
fmt.Println(sameTree(treeA, treeB), sameTree(treeA, treeC))
}
true false
The function compares the two roots, then both left sides, then both right sides. treeC has the same values but a different shape, so it is not the same tree.
Q7. How do you print the right side view of a tree?
Use the level order code from Program 4 and keep only the last value of each row. For our sample tree, the right side view is 50, 70 and 80.
Design Questions
Q8. Why do databases use B-trees instead of binary trees?
A B-tree node holds many keys and many children, so the tree is very short. Each level is one disk read, so fewer levels means far fewer slow reads.
Q9. How do you stop a BST from becoming a chain?
Use a self-balancing tree, such as a red-black tree or an AVL tree, which rotates nodes after inserts. Or shuffle the data before inserting it.
Q10. Where do trees appear in real Go code?
The go/ast package parses Go source code into a syntax tree. HTTP routers use prefix trees (tries) to match paths, and encoding/json decodes nested JSON into a tree of maps and slices.
Practice Task
To practise Go tree programs, write a function that returns every root-to-leaf path as a string, such as 50->30->20. For our sample tree, it should print four paths. Hint: pass the path so far into each recursive call and print when you reach a leaf.
Official Resources
- Pointers to structs in the Tour of Go
- go/ast package documentation
- The Go Programming Language Specification
Quick Recap
- Go tree programs use nodes with
LeftandRightpointers, starting at a root. - In a BST, left values are smaller and right values are bigger.
- Inorder gives sorted output, and level order uses a queue.
- Height, count and balance checks all combine answers from the two subtrees.
- Validate a BST with a range, and find the LCA where two values split.
What’s Next?
Next, we connect nodes in any direction, not just parent to child. Read Go graph programs, with BFS, DFS, shortest path and topological sort. For more practice, see the Go heap programs.


