{"id":854,"date":"2026-10-10T15:00:00","date_gmt":"2026-10-10T09:30:00","guid":{"rendered":"https:\/\/smitabharat.com\/blog\/go-tree-programs\/"},"modified":"2026-11-29T01:29:24","modified_gmt":"2026-11-28T19:59:24","slug":"go-tree-programs","status":"publish","type":"post","link":"https:\/\/smitabharat.com\/blog\/go-tree-programs\/","title":{"rendered":"Go Tree Programs: Binary Search Tree, Traversals, Height, LCA"},"content":{"rendered":"\n<p class=\"wp-block-paragraph\">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.<\/p>\n\n\n\n<p class=\"wp-block-paragraph\">You should first finish our <a href=\"https:\/\/smitabharat.com\/blog\/go-recursion-programs\/\">Go recursion programs<\/a>, because almost every tree function calls itself. The <a href=\"https:\/\/smitabharat.com\/blog\/go-linked-list-programs\/\">Go linked list programs<\/a> and <a href=\"https:\/\/smitabharat.com\/blog\/go-stack-and-queue-programs\/\">Go stack and queue programs<\/a> are useful too, since a tree node is a list node with two pointers. All programs were tested on Go 1.27.<\/p>\n\n\n\n<h2 class=\"wp-block-heading\">What are Go Tree Programs?<\/h2>\n\n\n\n<p class=\"wp-block-paragraph\">Go tree programs build nodes that point to child nodes. In a binary tree, each node has at most two children, called <code>Left<\/code> and <code>Right<\/code>. The top node is the root, and nodes with no children are called leaves.<\/p>\n\n\n\n<p class=\"wp-block-paragraph\">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.<\/p>\n\n\n\n<h2 class=\"wp-block-heading\">Why Go Tree Programs Matter<\/h2>\n\n\n\n<p class=\"wp-block-paragraph\">Trees appear wherever data has a natural &#8220;inside of&#8221; or &#8220;sorted&#8221; shape.<\/p>\n\n\n\n<ul class=\"wp-block-list\">\n<li><strong>Fast search:<\/strong> a balanced binary search tree finds a value in O(log n) steps.<\/li>\n\n\n<li><strong>Real data:<\/strong> folders, HTML pages, JSON and company org charts are all trees.<\/li>\n\n\n<li><strong>Databases:<\/strong> indexes use B-trees, a wider cousin of the binary search tree.<\/li>\n\n\n<li><strong>Interviews:<\/strong> traversals, height, validate BST and lowest common ancestor are very common.<\/li>\n\n<\/ul>\n\n\n\n<h2 class=\"wp-block-heading\">How Go Tree Programs Work<\/h2>\n\n\n\n<p class=\"wp-block-paragraph\">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.<\/p>\n\n\n\n<figure class=\"wp-block-image aligncenter size-large\"><img loading=\"lazy\" decoding=\"async\" width=\"1024\" height=\"640\" src=\"https:\/\/smitabharat.com\/blog\/wp-content\/uploads\/2026\/10\/go-tree-programs-diagram-1-1024x640.png\" alt=\"Go tree programs diagram showing a binary search tree with root 50 and smaller values on the left\" class=\"wp-image-852\" srcset=\"https:\/\/smitabharat.com\/blog\/wp-content\/uploads\/2026\/10\/go-tree-programs-diagram-1-1024x640.png 1024w, https:\/\/smitabharat.com\/blog\/wp-content\/uploads\/2026\/10\/go-tree-programs-diagram-1-300x188.png 300w, https:\/\/smitabharat.com\/blog\/wp-content\/uploads\/2026\/10\/go-tree-programs-diagram-1-768x480.png 768w, https:\/\/smitabharat.com\/blog\/wp-content\/uploads\/2026\/10\/go-tree-programs-diagram-1-1536x960.png 1536w, https:\/\/smitabharat.com\/blog\/wp-content\/uploads\/2026\/10\/go-tree-programs-diagram-1-2048x1280.png 2048w\" sizes=\"auto, (max-width: 1024px) 100vw, 1024px\" \/><figcaption class=\"wp-element-caption\">Every left child is smaller and every right child is bigger, so a search drops half the tree at each step.<\/figcaption><\/figure>\n\n\n\n<p class=\"wp-block-paragraph\">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.<\/p>\n\n\n\n<figure class=\"wp-block-table\"><table><thead><tr><th>Traversal<\/th><th>Order rule<\/th><th>Output<\/th><\/tr><\/thead><tbody><tr><td>Inorder<\/td><td>Left, node, right<\/td><td>20 30 40 50 60 70 80<\/td><\/tr><tr><td>Preorder<\/td><td>Node, left, right<\/td><td>50 30 20 40 70 60 80<\/td><\/tr><tr><td>Postorder<\/td><td>Left, right, node<\/td><td>20 40 30 60 80 70 50<\/td><\/tr><tr><td>Level order<\/td><td>Row by row, left to right<\/td><td>50 30 70 20 40 60 80<\/td><\/tr><\/tbody><\/table><\/figure>\n\n\n\n<h2 class=\"wp-block-heading\">Basic Go Tree Programs<\/h2>\n\n\n\n<p class=\"wp-block-paragraph\">These first Go tree programs make a tiny tree by hand, then build a BST and walk it in each of the four orders.<\/p>\n\n\n\n<h3 class=\"wp-block-heading\">Program 1: Make a Tiny Tree by Hand<\/h3>\n\n\n\n<pre class=\"wp-block-code\"><code>package main\n\nimport \"fmt\"\n\n\/\/ Node is one box in the tree. It holds a value and links to two children.\ntype Node struct {\n    Val   int   \/\/ the number stored in this node\n    Left  *Node \/\/ pointer to the left child (nil means \"no child\")\n    Right *Node \/\/ pointer to the right child\n}\n\nfunc main() {\n    \/\/ Step 1: make three separate nodes.\n    \/\/ := creates a new variable, and &amp; gives us a pointer to the new node.\n    root := &amp;Node{Val: 50}\n    leftChild := &amp;Node{Val: 30}\n    rightChild := &amp;Node{Val: 70}\n\n    \/\/ Step 2: link the two children to the root\n    root.Left = leftChild\n    root.Right = rightChild\n\n    \/\/ Step 3: reach each child through the root\n    fmt.Println(\"root:\", root.Val)\n    fmt.Println(\"left child:\", root.Left.Val)\n    fmt.Println(\"right child:\", root.Right.Val)\n\n    \/\/ A leaf has no children, so both of its links are nil (empty)\n    isLeaf := leftChild.Left == nil &amp;&amp; leftChild.Right == nil\n    fmt.Println(\"30 is a leaf:\", isLeaf)\n}<\/code><\/pre>\n\n\n\n<pre class=\"wp-block-code\"><code>root: 50\nleft child: 30\nright child: 70\n30 is a leaf: true<\/code><\/pre>\n\n\n\n<p class=\"wp-block-paragraph\">This is the smallest possible tree. First you create three nodes, then you set the root&#8217;s <code>Left<\/code> and <code>Right<\/code> links. After that, <code>root.Left.Val<\/code> follows the link from the root down to its child. The node 30 has no links of its own, so it is a leaf.<\/p>\n\n\n\n<h3 class=\"wp-block-heading\">Program 2: Build a BST and Print It Inorder<\/h3>\n\n\n\n<pre class=\"wp-block-code\"><code>package main\n\nimport \"fmt\"\n\n\/\/ Node is one item in the tree with links to its two children.\ntype Node struct {\n    Val         int\n    Left, Right *Node \/\/ two pointers of the same type on one line\n}\n\n\/\/ insert puts value in the right place and returns the root of the tree.\nfunc insert(root *Node, value int) *Node {\n    if root == nil {\n        return &amp;Node{Val: value} \/\/ empty spot found: create the node here\n    }\n    if value &lt; root.Val {\n        root.Left = insert(root.Left, value) \/\/ smaller values go left\n    } else {\n        root.Right = insert(root.Right, value) \/\/ bigger or equal go right\n    }\n    return root\n}\n\n\/\/ inorder visits left, then the node, then right.\n\/\/ For a BST, this prints the values in sorted order.\nfunc inorder(node *Node) {\n    if node == nil {\n        return \/\/ nothing here, so go back up\n    }\n    inorder(node.Left)\n    fmt.Print(node.Val, \" \")\n    inorder(node.Right)\n}\n\nfunc main() {\n    var root *Node \/\/ an empty tree starts as nil\n    \/\/ range gives each value of the slice, one by one\n    for _, value := range []int{50, 30, 70, 20, 40, 60, 80} {\n        root = insert(root, value)\n    }\n    inorder(root)\n    fmt.Println()\n}<\/code><\/pre>\n\n\n\n<pre class=\"wp-block-code\"><code>20 30 40 50 60 70 80<\/code><\/pre>\n\n\n\n<p class=\"wp-block-paragraph\">The <code>insert<\/code> 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.<\/p>\n\n\n\n<h3 class=\"wp-block-heading\">Program 3: Preorder and Postorder Traversal<\/h3>\n\n\n\n<pre class=\"wp-block-code\"><code>package main\n\nimport \"fmt\"\n\n\/\/ Node is one item in the tree with links to its two children.\ntype Node struct {\n    Val         int\n    Left, Right *Node\n}\n\n\/\/ insert adds value in the right place (same as Program 2).\nfunc insert(root *Node, value int) *Node {\n    if root == nil {\n        return &amp;Node{Val: value}\n    }\n    if value &lt; root.Val {\n        root.Left = insert(root.Left, value)\n    } else {\n        root.Right = insert(root.Right, value)\n    }\n    return root\n}\n\n\/\/ preorder visits the node first. Useful to copy or print a tree top-down.\nfunc preorder(node *Node, result *[]int) {\n    if node == nil {\n        return\n    }\n    *result = append(*result, node.Val) \/\/ *result means \"the slice the pointer points to\"\n    preorder(node.Left, result)\n    preorder(node.Right, result)\n}\n\n\/\/ postorder visits the children first. Useful to delete a tree or sum folder sizes.\nfunc postorder(node *Node, result *[]int) {\n    if node == nil {\n        return\n    }\n    postorder(node.Left, result)\n    postorder(node.Right, result)\n    *result = append(*result, node.Val) \/\/ the node comes last\n}\n\nfunc main() {\n    var root *Node\n    for _, value := range []int{50, 30, 70, 20, 40, 60, 80} {\n        root = insert(root, value)\n    }\n    var preList, postList []int\n    preorder(root, &amp;preList) \/\/ &amp;preList passes a pointer, so the function can grow it\n    postorder(root, &amp;postList)\n    fmt.Println(\"pre: \", preList)\n    fmt.Println(\"post:\", postList)\n}<\/code><\/pre>\n\n\n\n<pre class=\"wp-block-code\"><code>pre:  [50 30 20 40 70 60 80]\npost: [20 40 30 60 80 70 50]<\/code><\/pre>\n\n\n\n<p class=\"wp-block-paragraph\">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 &#8220;visit&#8221; line sits.<\/p>\n\n\n\n<h3 class=\"wp-block-heading\">Program 4: Level Order Traversal with a Queue<\/h3>\n\n\n\n<pre class=\"wp-block-code\"><code>package main\n\nimport \"fmt\"\n\n\/\/ Node is one item in the tree with links to its two children.\ntype Node struct {\n    Val         int\n    Left, Right *Node\n}\n\n\/\/ insert adds value in the right place (same as Program 2).\nfunc insert(root *Node, value int) *Node {\n    if root == nil {\n        return &amp;Node{Val: value}\n    }\n    if value &lt; root.Val {\n        root.Left = insert(root.Left, value)\n    } else {\n        root.Right = insert(root.Right, value)\n    }\n    return root\n}\n\n\/\/ levels returns one slice per row of the tree, from top to bottom.\nfunc levels(root *Node) [][]int {\n    var result [][]int\n    if root == nil {\n        return result\n    }\n    queue := []*Node{root} \/\/ a slice used as a queue: add at the back, take from the front\n    for len(queue) &gt; 0 {\n        size := len(queue) \/\/ number of nodes in this row\n        var row []int\n        for i := 0; i &lt; size; i++ {\n            \/\/ Step 1: take the first node out of the queue\n            current := queue[0]\n            queue = queue[1:] \/\/ [1:] keeps everything except the first item\n            row = append(row, current.Val)\n            \/\/ Step 2: its children join the queue for the next row\n            if current.Left != nil {\n                queue = append(queue, current.Left)\n            }\n            if current.Right != nil {\n                queue = append(queue, current.Right)\n            }\n        }\n        result = append(result, row)\n    }\n    return result\n}\n\nfunc main() {\n    var root *Node\n    for _, value := range []int{50, 30, 70, 20, 40, 60, 80} {\n        root = insert(root, value)\n    }\n    fmt.Println(levels(root))\n}<\/code><\/pre>\n\n\n\n<pre class=\"wp-block-code\"><code>[[50] [30 70] [20 40 60 80]]<\/code><\/pre>\n\n\n\n<p class=\"wp-block-paragraph\">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 <code>size<\/code> before the inner loop lets us split the output into rows. Questions like &#8220;right side view&#8221; and &#8220;zigzag order&#8221; reuse this exact pattern.<\/p>\n\n\n\n<figure class=\"wp-block-image aligncenter size-large\"><img loading=\"lazy\" decoding=\"async\" width=\"1024\" height=\"640\" src=\"https:\/\/smitabharat.com\/blog\/wp-content\/uploads\/2026\/10\/go-tree-programs-diagram-2-1024x640.png\" alt=\"Go tree programs comparison of depth-first and breadth-first traversal\" class=\"wp-image-853\" srcset=\"https:\/\/smitabharat.com\/blog\/wp-content\/uploads\/2026\/10\/go-tree-programs-diagram-2-1024x640.png 1024w, https:\/\/smitabharat.com\/blog\/wp-content\/uploads\/2026\/10\/go-tree-programs-diagram-2-300x188.png 300w, https:\/\/smitabharat.com\/blog\/wp-content\/uploads\/2026\/10\/go-tree-programs-diagram-2-768x480.png 768w, https:\/\/smitabharat.com\/blog\/wp-content\/uploads\/2026\/10\/go-tree-programs-diagram-2-1536x960.png 1536w, https:\/\/smitabharat.com\/blog\/wp-content\/uploads\/2026\/10\/go-tree-programs-diagram-2-2048x1280.png 2048w\" sizes=\"auto, (max-width: 1024px) 100vw, 1024px\" \/><figcaption class=\"wp-element-caption\">Depth-first goes down one branch before the next, while breadth-first visits the tree row by row.<\/figcaption><\/figure>\n\n\n\n<h2 class=\"wp-block-heading\">BST Go Tree Programs<\/h2>\n\n\n\n<p class=\"wp-block-paragraph\">These Go tree programs use the BST rule to place values, search, find limits and delete nodes.<\/p>\n\n\n\n<h3 class=\"wp-block-heading\">Program 5: Watch Where Each Value Goes in a BST<\/h3>\n\n\n\n<pre class=\"wp-block-code\"><code>package main\n\nimport \"fmt\"\n\n\/\/ Node is one item in the tree with links to its two children.\ntype Node struct {\n    Val         int\n    Left, Right *Node\n}\n\n\/\/ insertAndShow adds value to the tree and prints every turn it takes.\nfunc insertAndShow(root *Node, value int) *Node {\n    if root == nil {\n        fmt.Printf(\"  placed %d here\\n\", value) \/\/ %d prints a whole number\n        return &amp;Node{Val: value}\n    }\n    if value &lt; root.Val {\n        fmt.Printf(\"  %d &lt; %d, go left\\n\", value, root.Val)\n        root.Left = insertAndShow(root.Left, value)\n    } else {\n        fmt.Printf(\"  %d &gt;= %d, go right\\n\", value, root.Val)\n        root.Right = insertAndShow(root.Right, value)\n    }\n    return root\n}\n\nfunc main() {\n    var root *Node\n    for _, value := range []int{50, 30, 70, 40} {\n        fmt.Println(\"insert\", value)\n        root = insertAndShow(root, value)\n    }\n}<\/code><\/pre>\n\n\n\n<pre class=\"wp-block-code\"><code>insert 50\n  placed 50 here\ninsert 30\n  30 &lt; 50, go left\n  placed 30 here\ninsert 70\n  70 &gt;= 50, go right\n  placed 70 here\ninsert 40\n  40 &lt; 50, go left\n  40 &gt;= 30, go right\n  placed 40 here<\/code><\/pre>\n\n\n\n<p class=\"wp-block-paragraph\">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.<\/p>\n\n\n\n<h3 class=\"wp-block-heading\">Program 6: Search a BST<\/h3>\n\n\n\n<pre class=\"wp-block-code\"><code>package main\n\nimport \"fmt\"\n\n\/\/ Node is one item in the tree with links to its two children.\ntype Node struct {\n    Val         int\n    Left, Right *Node\n}\n\n\/\/ insert adds value in the right place (same as Program 2).\nfunc insert(root *Node, value int) *Node {\n    if root == nil {\n        return &amp;Node{Val: value}\n    }\n    if value &lt; root.Val {\n        root.Left = insert(root.Left, value)\n    } else {\n        root.Right = insert(root.Right, value)\n    }\n    return root\n}\n\n\/\/ search walks down without recursion and counts the steps.\n\/\/ It returns two values: whether target was found, and the step count.\nfunc search(root *Node, target int) (bool, int) {\n    steps := 0\n    current := root\n    for current != nil {\n        steps++\n        if target == current.Val {\n            return true, steps\n        } else if target &lt; current.Val {\n            current = current.Left \/\/ the target can only be on the left\n        } else {\n            current = current.Right \/\/ the target can only be on the right\n        }\n    }\n    return false, steps \/\/ we fell off the tree, so it is not there\n}\n\nfunc main() {\n    var root *Node\n    for _, value := range []int{50, 30, 70, 20, 40, 60, 80} {\n        root = insert(root, value)\n    }\n    fmt.Println(search(root, 60))\n    fmt.Println(search(root, 45))\n}<\/code><\/pre>\n\n\n\n<pre class=\"wp-block-code\"><code>true 3\nfalse 3<\/code><\/pre>\n\n\n\n<p class=\"wp-block-paragraph\">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.<\/p>\n\n\n\n<h3 class=\"wp-block-heading\">Program 7: Height, Node Count and Leaf Count<\/h3>\n\n\n\n<pre class=\"wp-block-code\"><code>package main\n\nimport \"fmt\"\n\n\/\/ Node is one item in the tree with links to its two children.\ntype Node struct {\n    Val         int\n    Left, Right *Node\n}\n\n\/\/ insert adds value in the right place (same as Program 2).\nfunc insert(root *Node, value int) *Node {\n    if root == nil {\n        return &amp;Node{Val: value}\n    }\n    if value &lt; root.Val {\n        root.Left = insert(root.Left, value)\n    } else {\n        root.Right = insert(root.Right, value)\n    }\n    return root\n}\n\n\/\/ height is 1 plus the taller of the two subtrees. An empty tree has height 0.\nfunc height(node *Node) int {\n    if node == nil {\n        return 0\n    }\n    leftHeight := height(node.Left)\n    rightHeight := height(node.Right)\n    return 1 + max(leftHeight, rightHeight) \/\/ max returns the bigger number\n}\n\n\/\/ count returns how many nodes the tree has.\nfunc count(node *Node) int {\n    if node == nil {\n        return 0\n    }\n    return 1 + count(node.Left) + count(node.Right)\n}\n\n\/\/ leaves returns how many nodes have no children.\nfunc leaves(node *Node) int {\n    if node == nil {\n        return 0\n    }\n    if node.Left == nil &amp;&amp; node.Right == nil {\n        return 1 \/\/ no children, so this is a leaf\n    }\n    return leaves(node.Left) + leaves(node.Right)\n}\n\nfunc main() {\n    var root *Node\n    for _, value := range []int{50, 30, 70, 20, 40, 60, 80, 10} {\n        root = insert(root, value)\n    }\n    fmt.Println(\"height:\", height(root), \"nodes:\", count(root), \"leaves:\", leaves(root))\n}<\/code><\/pre>\n\n\n\n<pre class=\"wp-block-code\"><code>height: 4 nodes: 8 leaves: 4<\/code><\/pre>\n\n\n\n<p class=\"wp-block-paragraph\">Many Go tree programs share this shape, and all three functions here follow it. First you handle <code>nil<\/code>, 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.<\/p>\n\n\n\n<h3 class=\"wp-block-heading\">Program 8: Smallest and Largest Value in a BST<\/h3>\n\n\n\n<pre class=\"wp-block-code\"><code>package main\n\nimport \"fmt\"\n\n\/\/ Node is one item in the tree with links to its two children.\ntype Node struct {\n    Val         int\n    Left, Right *Node\n}\n\n\/\/ insert adds value in the right place (same as Program 2).\nfunc insert(root *Node, value int) *Node {\n    if root == nil {\n        return &amp;Node{Val: value}\n    }\n    if value &lt; root.Val {\n        root.Left = insert(root.Left, value)\n    } else {\n        root.Right = insert(root.Right, value)\n    }\n    return root\n}\n\n\/\/ minNode keeps going left. The leftmost node holds the smallest value.\nfunc minNode(node *Node) *Node {\n    for node.Left != nil {\n        node = node.Left\n    }\n    return node\n}\n\n\/\/ maxNode keeps going right. The rightmost node holds the largest value.\nfunc maxNode(node *Node) *Node {\n    for node.Right != nil {\n        node = node.Right\n    }\n    return node\n}\n\nfunc main() {\n    var root *Node\n    for _, value := range []int{50, 30, 70, 20, 40, 60, 80} {\n        root = insert(root, value)\n    }\n    fmt.Println(minNode(root).Val, maxNode(root).Val)\n}<\/code><\/pre>\n\n\n\n<pre class=\"wp-block-code\"><code>20 80<\/code><\/pre>\n\n\n\n<p class=\"wp-block-paragraph\">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.<\/p>\n\n\n\n<h3 class=\"wp-block-heading\">Program 9: Delete a Node from a BST<\/h3>\n\n\n\n<pre class=\"wp-block-code\"><code>package main\n\nimport \"fmt\"\n\n\/\/ Node is one item in the tree with links to its two children.\ntype Node struct {\n    Val         int\n    Left, Right *Node\n}\n\n\/\/ insert adds value in the right place (same as Program 2).\nfunc insert(root *Node, value int) *Node {\n    if root == nil {\n        return &amp;Node{Val: value}\n    }\n    if value &lt; root.Val {\n        root.Left = insert(root.Left, value)\n    } else {\n        root.Right = insert(root.Right, value)\n    }\n    return root\n}\n\n\/\/ inorder prints the values in sorted order.\nfunc inorder(node *Node) {\n    if node != nil {\n        inorder(node.Left)\n        fmt.Print(node.Val, \" \")\n        inorder(node.Right)\n    }\n}\n\n\/\/ remove deletes value and returns the new root of this subtree.\nfunc remove(node *Node, value int) *Node {\n    if node == nil {\n        return nil \/\/ value not found\n    }\n    if value &lt; node.Val {\n        node.Left = remove(node.Left, value)\n        return node\n    }\n    if value &gt; node.Val {\n        node.Right = remove(node.Right, value)\n        return node\n    }\n    \/\/ Step 1: we found the node. With 0 or 1 child, the child takes its place.\n    if node.Left == nil {\n        return node.Right\n    }\n    if node.Right == nil {\n        return node.Left\n    }\n    \/\/ Step 2: with 2 children, find the smallest value on the right side\n    successor := node.Right\n    for successor.Left != nil {\n        successor = successor.Left\n    }\n    \/\/ Step 3: copy that value here, then delete the old copy on the right\n    node.Val = successor.Val\n    node.Right = remove(node.Right, successor.Val)\n    return node\n}\n\nfunc main() {\n    var root *Node\n    for _, value := range []int{50, 30, 70, 20, 40, 60, 80} {\n        root = insert(root, value)\n    }\n    root = remove(root, 20) \/\/ a leaf\n    root = remove(root, 50) \/\/ the root, which has two children\n    inorder(root)\n    fmt.Println(\"| root:\", root.Val)\n}<\/code><\/pre>\n\n\n\n<pre class=\"wp-block-code\"><code>30 40 60 70 80 | root: 60<\/code><\/pre>\n\n\n\n<p class=\"wp-block-paragraph\">Deleting 20 is easy because it is a leaf, so its parent simply gets <code>nil<\/code>. 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.<\/p>\n\n\n\n<h2 class=\"wp-block-heading\">Most Asked Interview Go Tree Programs<\/h2>\n\n\n\n<p class=\"wp-block-paragraph\">These Go tree programs are the ones interviewers ask most often.<\/p>\n\n\n\n<h3 class=\"wp-block-heading\">Program 10: Check if a Tree is a Valid BST<\/h3>\n\n\n\n<pre class=\"wp-block-code\"><code>package main\n\nimport (\n    \"fmt\"\n    \"math\"\n)\n\n\/\/ Node is one item in the tree with links to its two children.\ntype Node struct {\n    Val         int\n    Left, Right *Node\n}\n\n\/\/ isValid checks that every value sits inside the allowed range (low, high).\nfunc isValid(node *Node, low, high int) bool {\n    if node == nil {\n        return true \/\/ an empty tree breaks no rules\n    }\n    if node.Val &lt;= low || node.Val &gt;= high {\n        return false \/\/ value breaks a rule set by an ancestor\n    }\n    \/\/ left side must stay below node.Val, right side must stay above it\n    leftOK := isValid(node.Left, low, node.Val)\n    rightOK := isValid(node.Right, node.Val, high)\n    return leftOK &amp;&amp; rightOK\n}\n\nfunc main() {\n    \/\/ &amp;Node{50, left, right} fills Val, Left and Right in order\n    good := &amp;Node{50, &amp;Node{30, nil, nil}, &amp;Node{70, nil, nil}}\n    \/\/ 60 is right of 30, but it is in the LEFT subtree of 50, so it is wrong\n    bad := &amp;Node{50, &amp;Node{30, nil, &amp;Node{60, nil, nil}}, &amp;Node{70, nil, nil}}\n\n    \/\/ math.MinInt and math.MaxInt are the smallest and largest int values\n    fmt.Println(isValid(good, math.MinInt, math.MaxInt))\n    fmt.Println(isValid(bad, math.MinInt, math.MaxInt))\n}<\/code><\/pre>\n\n\n\n<pre class=\"wp-block-code\"><code>true\nfalse<\/code><\/pre>\n\n\n\n<p class=\"wp-block-paragraph\">The root may hold any value, so its range is the whole int range. When you go left, the node&#8217;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 <code>bad<\/code> tree passes that weak test.<\/p>\n\n\n\n<h3 class=\"wp-block-heading\">Program 11: Lowest Common Ancestor in a BST<\/h3>\n\n\n\n<pre class=\"wp-block-code\"><code>package main\n\nimport \"fmt\"\n\n\/\/ Node is one item in the tree with links to its two children.\ntype Node struct {\n    Val         int\n    Left, Right *Node\n}\n\n\/\/ insert adds value in the right place (same as Program 2).\nfunc insert(root *Node, value int) *Node {\n    if root == nil {\n        return &amp;Node{Val: value}\n    }\n    if value &lt; root.Val {\n        root.Left = insert(root.Left, value)\n    } else {\n        root.Right = insert(root.Right, value)\n    }\n    return root\n}\n\n\/\/ lca walks down until first and second split to different sides.\nfunc lca(root *Node, first, second int) *Node {\n    current := root\n    for current != nil {\n        if first &lt; current.Val &amp;&amp; second &lt; current.Val {\n            current = current.Left \/\/ both are smaller, so go left\n        } else if first &gt; current.Val &amp;&amp; second &gt; current.Val {\n            current = current.Right \/\/ both are bigger, so go right\n        } else {\n            return current \/\/ they split here, or one of them is this node\n        }\n    }\n    return nil\n}\n\nfunc main() {\n    var root *Node\n    for _, value := range []int{50, 30, 70, 20, 40, 60, 80} {\n        root = insert(root, value)\n    }\n    fmt.Println(lca(root, 20, 40).Val, lca(root, 20, 80).Val, lca(root, 60, 70).Val)\n}<\/code><\/pre>\n\n\n\n<pre class=\"wp-block-code\"><code>30 50 70<\/code><\/pre>\n\n\n\n<p class=\"wp-block-paragraph\">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.<\/p>\n\n\n\n<h3 class=\"wp-block-heading\">Program 12: Invert (Mirror) a Binary Tree<\/h3>\n\n\n\n<pre class=\"wp-block-code\"><code>package main\n\nimport \"fmt\"\n\n\/\/ Node is one item in the tree with links to its two children.\ntype Node struct {\n    Val         int\n    Left, Right *Node\n}\n\n\/\/ invert swaps the left and right children of every node.\nfunc invert(node *Node) *Node {\n    if node == nil {\n        return nil\n    }\n    \/\/ Step 1: mirror both subtrees first\n    newLeft := invert(node.Right)\n    newRight := invert(node.Left)\n    \/\/ Step 2: attach them on the opposite sides\n    node.Left = newLeft\n    node.Right = newRight\n    return node\n}\n\n\/\/ preorder prints the node, then its left side, then its right side.\nfunc preorder(node *Node) {\n    if node != nil {\n        fmt.Print(node.Val, \" \")\n        preorder(node.Left)\n        preorder(node.Right)\n    }\n}\n\nfunc main() {\n    root := &amp;Node{4, &amp;Node{2, &amp;Node{1, nil, nil}, &amp;Node{3, nil, nil}},\n        &amp;Node{7, &amp;Node{6, nil, nil}, &amp;Node{9, nil, nil}}}\n    preorder(root)\n    fmt.Println()\n    preorder(invert(root))\n    fmt.Println()\n}<\/code><\/pre>\n\n\n\n<pre class=\"wp-block-code\"><code>4 2 1 3 7 6 9\n4 7 9 6 2 3 1<\/code><\/pre>\n\n\n\n<p class=\"wp-block-paragraph\">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).<\/p>\n\n\n\n<h3 class=\"wp-block-heading\">Program 13: Check if a Tree is Balanced<\/h3>\n\n\n\n<pre class=\"wp-block-code\"><code>package main\n\nimport \"fmt\"\n\n\/\/ Node is one item in the tree with links to its two children.\ntype Node struct {\n    Val         int\n    Left, Right *Node\n}\n\n\/\/ checkHeight returns the height, or -1 as soon as any subtree is unbalanced.\nfunc checkHeight(node *Node) int {\n    if node == nil {\n        return 0\n    }\n    leftHeight := checkHeight(node.Left)\n    rightHeight := checkHeight(node.Right)\n    \/\/ Step 1: pass the -1 signal up if a subtree is already unbalanced\n    if leftHeight == -1 || rightHeight == -1 {\n        return -1\n    }\n    \/\/ Step 2: the two heights may differ by at most 1\n    if leftHeight-rightHeight &gt; 1 || rightHeight-leftHeight &gt; 1 {\n        return -1\n    }\n    return 1 + max(leftHeight, rightHeight)\n}\n\nfunc main() {\n    balanced := &amp;Node{2, &amp;Node{1, nil, nil}, &amp;Node{3, nil, nil}}\n    chain := &amp;Node{1, nil, &amp;Node{2, nil, &amp;Node{3, nil, nil}}} \/\/ like a linked list\n\n    fmt.Println(checkHeight(balanced) != -1, checkHeight(chain) != -1)\n}<\/code><\/pre>\n\n\n\n<pre class=\"wp-block-code\"><code>true false<\/code><\/pre>\n\n\n\n<p class=\"wp-block-paragraph\">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 <code>height<\/code> separately at every node would be O(n squared).<\/p>\n\n\n\n<h3 class=\"wp-block-heading\">Program 14: Inorder Traversal Without Recursion<\/h3>\n\n\n\n<pre class=\"wp-block-code\"><code>package main\n\nimport \"fmt\"\n\n\/\/ Node is one item in the tree with links to its two children.\ntype Node struct {\n    Val         int\n    Left, Right *Node\n}\n\n\/\/ inorderLoop uses a stack slice instead of recursive calls.\nfunc inorderLoop(root *Node) []int {\n    var result []int\n    var stack []*Node\n    current := root\n    for current != nil || len(stack) &gt; 0 {\n        \/\/ Step 1: go as far left as possible, saving each node on the stack\n        for current != nil {\n            stack = append(stack, current)\n            current = current.Left\n        }\n        \/\/ Step 2: take the last saved node off the stack and visit it\n        current = stack[len(stack)-1]\n        stack = stack[:len(stack)-1] \/\/ [:len-1] drops the last item\n        result = append(result, current.Val)\n        \/\/ Step 3: then handle its right subtree\n        current = current.Right\n    }\n    return result\n}\n\nfunc main() {\n    root := &amp;Node{50, &amp;Node{30, &amp;Node{20, nil, nil}, &amp;Node{40, nil, nil}},\n        &amp;Node{70, &amp;Node{60, nil, nil}, &amp;Node{80, nil, nil}}}\n    fmt.Println(inorderLoop(root))\n}<\/code><\/pre>\n\n\n\n<pre class=\"wp-block-code\"><code>[20 30 40 50 60 70 80]<\/code><\/pre>\n\n\n\n<p class=\"wp-block-paragraph\">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.<\/p>\n\n\n\n<h2 class=\"wp-block-heading\">BST vs Slice in Go Tree Programs<\/h2>\n\n\n\n<p class=\"wp-block-paragraph\">A sorted slice also gives fast search with binary search, so when is a tree better? The table below compares them.<\/p>\n\n\n\n<figure class=\"wp-block-table\"><table><thead><tr><th>Feature<\/th><th>Balanced BST<\/th><th>Sorted slice<\/th><\/tr><\/thead><tbody><tr><td>Search<\/td><td>O(log n)<\/td><td>O(log n)<\/td><\/tr><tr><td>Insert<\/td><td>O(log n)<\/td><td>O(n), shifts items<\/td><\/tr><tr><td>Delete<\/td><td>O(log n)<\/td><td>O(n), shifts items<\/td><\/tr><tr><td>Memory<\/td><td>Two pointers per node<\/td><td>Values only<\/td><\/tr><tr><td>Worst case<\/td><td>O(n) if it becomes a chain<\/td><td>Always the same<\/td><\/tr><\/tbody><\/table><\/figure>\n\n\n\n<p class=\"wp-block-paragraph\">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.<\/p>\n\n\n\n<h2 class=\"wp-block-heading\">Common Mistakes in Go Tree Programs<\/h2>\n\n\n\n<ul class=\"wp-block-list\">\n<li><strong>Forgetting the nil check:<\/strong> every recursive function must handle <code>node == nil<\/code> first.<\/li>\n\n\n<li><strong>Not returning the root:<\/strong> <code>insert<\/code> and <code>remove<\/code> must return the node so parents can relink.<\/li>\n\n\n<li><strong>Validating only parent and child:<\/strong> use a range, as in Program 10.<\/li>\n\n\n<li><strong>Inserting sorted data:<\/strong> 1, 2, 3, 4 turns a BST into a slow chain.<\/li>\n\n\n<li><strong>Mixing up height and depth:<\/strong> height counts down to the leaves, depth counts up to the root.<\/li>\n\n<\/ul>\n\n\n\n<h2 class=\"wp-block-heading\">Best Practices for Go Tree Programs<\/h2>\n\n\n\n<ul class=\"wp-block-list\">\n<li><strong>Write the nil case first,<\/strong> then the rule for one node.<\/li>\n\n\n<li><strong>Use level order with a queue<\/strong> for any &#8220;row by row&#8221; question.<\/li>\n\n\n<li><strong>Return -1 or an ok flag<\/strong> to stop early, as in the balanced check.<\/li>\n\n\n<li><strong>Use iteration for very deep trees<\/strong> to avoid huge call stacks.<\/li>\n\n\n<li><strong>Draw a small tree of 5 to 7 nodes<\/strong> and trace your code by hand.<\/li>\n\n<\/ul>\n\n\n\n<h2 class=\"wp-block-heading\">Go Tree Programs Interview Questions and Answers<\/h2>\n\n\n\n<p class=\"wp-block-paragraph\">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.<\/p>\n\n\n\n<h3 class=\"wp-block-heading\">Concept Questions on Go Tree Programs<\/h3>\n\n\n\n<p class=\"wp-block-paragraph\"><strong>Q1. What is the difference between a binary tree and a binary search tree?<\/strong><\/p>\n\n\n\n<p class=\"wp-block-paragraph\">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.<\/p>\n\n\n\n<p class=\"wp-block-paragraph\"><strong>Q2. What is the height of a tree with one node?<\/strong><\/p>\n\n\n\n<p class=\"wp-block-paragraph\">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.<\/p>\n\n\n\n<p class=\"wp-block-paragraph\"><strong>Q3. Which traversal gives sorted output for a BST?<\/strong><\/p>\n\n\n\n<p class=\"wp-block-paragraph\">Inorder traversal: left, node, right. Preorder and postorder do not give sorted output.<\/p>\n\n\n\n<p class=\"wp-block-paragraph\"><strong>Q4. What does this program print?<\/strong><\/p>\n\n\n\n<pre class=\"wp-block-code\"><code>package main\n\nimport \"fmt\"\n\n\/\/ Node is one item in the tree with links to its two children.\ntype Node struct {\n    Val         int\n    Left, Right *Node\n}\n\n\/\/ sum adds up every value in the tree.\nfunc sum(node *Node) int {\n    if node == nil {\n        return 0\n    }\n    return node.Val + sum(node.Left) + sum(node.Right) \/\/ node plus both subtrees\n}\n\nfunc main() {\n    root := &amp;Node{10, &amp;Node{5, nil, &amp;Node{2, nil, nil}}, &amp;Node{-3, nil, nil}}\n    fmt.Println(sum(root))\n}<\/code><\/pre>\n\n\n\n<pre class=\"wp-block-code\"><code>14<\/code><\/pre>\n\n\n\n<p class=\"wp-block-paragraph\">10 + 5 + 2 &#8211; 3 is 14. Every node is visited once.<\/p>\n\n\n\n<h3 class=\"wp-block-heading\">Coding Questions<\/h3>\n\n\n\n<p class=\"wp-block-paragraph\"><strong>Q5. How do you find the kth smallest value in a BST?<\/strong><\/p>\n\n\n\n<pre class=\"wp-block-code\"><code>package main\n\nimport \"fmt\"\n\n\/\/ Node is one item in the tree with links to its two children.\ntype Node struct {\n    Val         int\n    Left, Right *Node\n}\n\n\/\/ walk does an inorder visit and stops at the kth node.\n\/\/ count and answer are pointers, so every call shares the same two numbers.\nfunc walk(node *Node, k int, count *int, answer *int) {\n    if node == nil || *count &gt;= k {\n        return\n    }\n    walk(node.Left, k, count, answer)\n    *count = *count + 1\n    if *count == k {\n        *answer = node.Val\n        return\n    }\n    walk(node.Right, k, count, answer)\n}\n\n\/\/ kthSmallest returns the kth smallest value, or -1 if the tree is too small.\nfunc kthSmallest(root *Node, k int) int {\n    count := 0\n    answer := -1\n    walk(root, k, &amp;count, &amp;answer)\n    return answer\n}\n\nfunc main() {\n    root := &amp;Node{50, &amp;Node{30, &amp;Node{20, nil, nil}, &amp;Node{40, nil, nil}},\n        &amp;Node{70, &amp;Node{60, nil, nil}, &amp;Node{80, nil, nil}}}\n    fmt.Println(kthSmallest(root, 3), kthSmallest(root, 6))\n}<\/code><\/pre>\n\n\n\n<pre class=\"wp-block-code\"><code>40 70<\/code><\/pre>\n\n\n\n<p class=\"wp-block-paragraph\">Inorder gives sorted order, so the kth visit is the kth smallest. The <code>walk<\/code> function adds 1 to <code>count<\/code> at each visit. When <code>count<\/code> reaches <code>k<\/code>, it saves the value in <code>answer<\/code> and stops.<\/p>\n\n\n\n<p class=\"wp-block-paragraph\"><strong>Q6. How do you check if two trees are the same?<\/strong><\/p>\n\n\n\n<pre class=\"wp-block-code\"><code>package main\n\nimport \"fmt\"\n\n\/\/ Node is one item in the tree with links to its two children.\ntype Node struct {\n    Val         int\n    Left, Right *Node\n}\n\n\/\/ sameTree reports whether two trees have the same shape and values.\nfunc sameTree(first, second *Node) bool {\n    if first == nil || second == nil {\n        return first == second \/\/ both nil is true, only one nil is false\n    }\n    if first.Val != second.Val {\n        return false\n    }\n    return sameTree(first.Left, second.Left) &amp;&amp; sameTree(first.Right, second.Right)\n}\n\nfunc main() {\n    treeA := &amp;Node{1, &amp;Node{2, nil, nil}, nil}\n    treeB := &amp;Node{1, &amp;Node{2, nil, nil}, nil}\n    treeC := &amp;Node{1, nil, &amp;Node{2, nil, nil}}\n    fmt.Println(sameTree(treeA, treeB), sameTree(treeA, treeC))\n}<\/code><\/pre>\n\n\n\n<pre class=\"wp-block-code\"><code>true false<\/code><\/pre>\n\n\n\n<p class=\"wp-block-paragraph\">The function compares the two roots, then both left sides, then both right sides. <code>treeC<\/code> has the same values but a different shape, so it is not the same tree.<\/p>\n\n\n\n<p class=\"wp-block-paragraph\"><strong>Q7. How do you print the right side view of a tree?<\/strong><\/p>\n\n\n\n<p class=\"wp-block-paragraph\">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.<\/p>\n\n\n\n<h3 class=\"wp-block-heading\">Design Questions<\/h3>\n\n\n\n<p class=\"wp-block-paragraph\"><strong>Q8. Why do databases use B-trees instead of binary trees?<\/strong><\/p>\n\n\n\n<p class=\"wp-block-paragraph\">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.<\/p>\n\n\n\n<p class=\"wp-block-paragraph\"><strong>Q9. How do you stop a BST from becoming a chain?<\/strong><\/p>\n\n\n\n<p class=\"wp-block-paragraph\">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.<\/p>\n\n\n\n<p class=\"wp-block-paragraph\"><strong>Q10. Where do trees appear in real Go code?<\/strong><\/p>\n\n\n\n<p class=\"wp-block-paragraph\">The <code>go\/ast<\/code> package parses Go source code into a syntax tree. HTTP routers use prefix trees (tries) to match paths, and <code>encoding\/json<\/code> decodes nested JSON into a tree of maps and slices.<\/p>\n\n\n\n<h2 class=\"wp-block-heading\">Practice Task<\/h2>\n\n\n\n<p class=\"wp-block-paragraph\">To practise Go tree programs, write a function that returns every root-to-leaf path as a string, such as <code>50-&gt;30-&gt;20<\/code>. 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.<\/p>\n\n\n\n<h2 class=\"wp-block-heading\">Official Resources<\/h2>\n\n\n\n<ul class=\"wp-block-list\">\n<li><a href=\"https:\/\/go.dev\/tour\/moretypes\/4\">Pointers to structs in the Tour of Go<\/a><\/li>\n\n\n<li><a href=\"https:\/\/pkg.go.dev\/go\/ast\">go\/ast package documentation<\/a><\/li>\n\n\n<li><a href=\"https:\/\/go.dev\/ref\/spec\">The Go Programming Language Specification<\/a><\/li>\n\n<\/ul>\n\n\n\n<h2 class=\"wp-block-heading\">Quick Recap<\/h2>\n\n\n\n<ul class=\"wp-block-list\">\n<li>Go tree programs use nodes with <code>Left<\/code> and <code>Right<\/code> pointers, starting at a root.<\/li>\n\n\n<li>In a BST, left values are smaller and right values are bigger.<\/li>\n\n\n<li>Inorder gives sorted output, and level order uses a queue.<\/li>\n\n\n<li>Height, count and balance checks all combine answers from the two subtrees.<\/li>\n\n\n<li>Validate a BST with a range, and find the LCA where two values split.<\/li>\n\n<\/ul>\n\n\n\n<h2 class=\"wp-block-heading\">What&#8217;s Next?<\/h2>\n\n\n\n<p class=\"wp-block-paragraph\">Next, we connect nodes in any direction, not just parent to child. Read <a href=\"https:\/\/smitabharat.com\/blog\/go-graph-programs\/\">Go graph programs<\/a>, with BFS, DFS, shortest path and topological sort. For more practice, see the <a href=\"https:\/\/smitabharat.com\/blog\/go-heap-programs\/\">Go heap programs<\/a>.<\/p>\n","protected":false},"excerpt":{"rendered":"<p>Go tree programs teach you how to store data in a branching shape, where each item can have children below it. In this post,&hellip;<\/p>\n","protected":false},"author":1,"featured_media":851,"comment_status":"closed","ping_status":"closed","sticky":false,"template":"","format":"standard","meta":{"_swapz_level":"","_swapz_series_part":0,"_swapz_hide_toc":false,"_swapz_hide_featured":false,"_swapz_description":"","footnotes":""},"categories":[106],"tags":[96,95,11,104,122],"swapz_series":[],"class_list":["post-854","post","type-post","status-publish","format-standard","has-post-thumbnail","hentry","category-go-programs","tag-beginner","tag-go-interview-questions","tag-go-lang","tag-go-programs","tag-go-trees"],"yoast_head":"<!-- This site is optimized with the Yoast SEO plugin v28.9 - https:\/\/yoast.com\/product\/yoast-seo-wordpress\/ -->\n<title>Go Tree Programs: BST, Traversals, Height, LCA<\/title>\n<meta name=\"description\" content=\"Go tree programs with output: binary search tree insert, search and delete, four traversals, height, validate BST and LCA, plus tree interview Q&amp;A.\" \/>\n<meta name=\"robots\" content=\"index, follow, max-snippet:-1, max-image-preview:large, max-video-preview:-1\" \/>\n<link rel=\"canonical\" href=\"https:\/\/smitabharat.com\/blog\/go-tree-programs\/\" \/>\n<meta property=\"og:locale\" content=\"en_US\" \/>\n<meta property=\"og:type\" content=\"article\" \/>\n<meta property=\"og:title\" content=\"Go Tree Programs: BST, Traversals, Height, LCA\" \/>\n<meta property=\"og:description\" content=\"Go tree programs with output: binary search tree insert, search and delete, four traversals, height, validate BST and LCA, plus tree interview Q&amp;A.\" \/>\n<meta property=\"og:url\" content=\"https:\/\/smitabharat.com\/blog\/go-tree-programs\/\" \/>\n<meta property=\"og:site_name\" content=\"Smita Bharat - Blog\" \/>\n<meta property=\"article:published_time\" content=\"2026-10-10T09:30:00+00:00\" \/>\n<meta property=\"article:modified_time\" content=\"2026-11-28T19:59:24+00:00\" \/>\n<meta property=\"og:image\" content=\"https:\/\/smitabharat.com\/blog\/wp-content\/uploads\/2026\/10\/go-tree-programs-featured.png\" \/>\n\t<meta property=\"og:image:width\" content=\"2400\" \/>\n\t<meta property=\"og:image:height\" content=\"1260\" \/>\n\t<meta property=\"og:image:type\" content=\"image\/png\" \/>\n<meta name=\"author\" content=\"Smita\" \/>\n<meta name=\"twitter:card\" content=\"summary_large_image\" \/>\n<meta name=\"twitter:label1\" content=\"Written by\" \/>\n\t<meta name=\"twitter:data1\" content=\"Smita\" \/>\n\t<meta name=\"twitter:label2\" content=\"Est. reading time\" \/>\n\t<meta name=\"twitter:data2\" content=\"24 minutes\" \/>\n<script type=\"application\/ld+json\" class=\"yoast-schema-graph\">{\"@context\":\"https:\\\/\\\/schema.org\",\"@graph\":[{\"@type\":\"Article\",\"@id\":\"https:\\\/\\\/smitabharat.com\\\/blog\\\/go-tree-programs\\\/#article\",\"isPartOf\":{\"@id\":\"https:\\\/\\\/smitabharat.com\\\/blog\\\/go-tree-programs\\\/\"},\"author\":{\"name\":\"Smita\",\"@id\":\"https:\\\/\\\/smitabharat.com\\\/blog\\\/#\\\/schema\\\/person\\\/27a1b1067d396703215c54acedbfd339\"},\"headline\":\"Go Tree Programs: Binary Search Tree, Traversals, Height, LCA\",\"datePublished\":\"2026-10-10T09:30:00+00:00\",\"dateModified\":\"2026-11-28T19:59:24+00:00\",\"mainEntityOfPage\":{\"@id\":\"https:\\\/\\\/smitabharat.com\\\/blog\\\/go-tree-programs\\\/\"},\"wordCount\":2015,\"publisher\":{\"@id\":\"https:\\\/\\\/smitabharat.com\\\/blog\\\/#\\\/schema\\\/person\\\/27a1b1067d396703215c54acedbfd339\"},\"image\":{\"@id\":\"https:\\\/\\\/smitabharat.com\\\/blog\\\/go-tree-programs\\\/#primaryimage\"},\"thumbnailUrl\":\"https:\\\/\\\/smitabharat.com\\\/blog\\\/wp-content\\\/uploads\\\/2026\\\/10\\\/go-tree-programs-featured.png\",\"keywords\":[\"Beginner\",\"Go Interview Questions\",\"Go Lang\",\"Go Programs\",\"Go Trees\"],\"articleSection\":[\"Go Programs\"],\"inLanguage\":\"en-US\"},{\"@type\":\"WebPage\",\"@id\":\"https:\\\/\\\/smitabharat.com\\\/blog\\\/go-tree-programs\\\/\",\"url\":\"https:\\\/\\\/smitabharat.com\\\/blog\\\/go-tree-programs\\\/\",\"name\":\"Go Tree Programs: BST, Traversals, Height, LCA\",\"isPartOf\":{\"@id\":\"https:\\\/\\\/smitabharat.com\\\/blog\\\/#website\"},\"primaryImageOfPage\":{\"@id\":\"https:\\\/\\\/smitabharat.com\\\/blog\\\/go-tree-programs\\\/#primaryimage\"},\"image\":{\"@id\":\"https:\\\/\\\/smitabharat.com\\\/blog\\\/go-tree-programs\\\/#primaryimage\"},\"thumbnailUrl\":\"https:\\\/\\\/smitabharat.com\\\/blog\\\/wp-content\\\/uploads\\\/2026\\\/10\\\/go-tree-programs-featured.png\",\"datePublished\":\"2026-10-10T09:30:00+00:00\",\"dateModified\":\"2026-11-28T19:59:24+00:00\",\"description\":\"Go tree programs with output: binary search tree insert, search and delete, four traversals, height, validate BST and LCA, plus tree interview Q&A.\",\"breadcrumb\":{\"@id\":\"https:\\\/\\\/smitabharat.com\\\/blog\\\/go-tree-programs\\\/#breadcrumb\"},\"inLanguage\":\"en-US\",\"potentialAction\":[{\"@type\":\"ReadAction\",\"target\":[\"https:\\\/\\\/smitabharat.com\\\/blog\\\/go-tree-programs\\\/\"]}]},{\"@type\":\"ImageObject\",\"inLanguage\":\"en-US\",\"@id\":\"https:\\\/\\\/smitabharat.com\\\/blog\\\/go-tree-programs\\\/#primaryimage\",\"url\":\"https:\\\/\\\/smitabharat.com\\\/blog\\\/wp-content\\\/uploads\\\/2026\\\/10\\\/go-tree-programs-featured.png\",\"contentUrl\":\"https:\\\/\\\/smitabharat.com\\\/blog\\\/wp-content\\\/uploads\\\/2026\\\/10\\\/go-tree-programs-featured.png\",\"width\":2400,\"height\":1260,\"caption\":\"Go Tree Programs featured image: BST traversal and height output\"},{\"@type\":\"BreadcrumbList\",\"@id\":\"https:\\\/\\\/smitabharat.com\\\/blog\\\/go-tree-programs\\\/#breadcrumb\",\"itemListElement\":[{\"@type\":\"ListItem\",\"position\":1,\"name\":\"Home\",\"item\":\"https:\\\/\\\/smitabharat.com\\\/blog\\\/\"},{\"@type\":\"ListItem\",\"position\":2,\"name\":\"Go Tree Programs: Binary Search Tree, Traversals, Height, LCA\"}]},{\"@type\":\"WebSite\",\"@id\":\"https:\\\/\\\/smitabharat.com\\\/blog\\\/#website\",\"url\":\"https:\\\/\\\/smitabharat.com\\\/blog\\\/\",\"name\":\"Smita Bharat Blog\",\"description\":\"Golang &amp; Backend Development Tutorials and Interview Questions\",\"publisher\":{\"@id\":\"https:\\\/\\\/smitabharat.com\\\/blog\\\/#\\\/schema\\\/person\\\/27a1b1067d396703215c54acedbfd339\"},\"alternateName\":\"Smita Bharat\",\"potentialAction\":[{\"@type\":\"SearchAction\",\"target\":{\"@type\":\"EntryPoint\",\"urlTemplate\":\"https:\\\/\\\/smitabharat.com\\\/blog\\\/?s={search_term_string}\"},\"query-input\":{\"@type\":\"PropertyValueSpecification\",\"valueRequired\":true,\"valueName\":\"search_term_string\"}}],\"inLanguage\":\"en-US\"},{\"@type\":[\"Person\",\"Organization\"],\"@id\":\"https:\\\/\\\/smitabharat.com\\\/blog\\\/#\\\/schema\\\/person\\\/27a1b1067d396703215c54acedbfd339\",\"name\":\"Smita\",\"logo\":{\"@id\":\"https:\\\/\\\/smitabharat.com\\\/blog\\\/#\\\/schema\\\/person\\\/image\\\/\"},\"sameAs\":[\"https:\\\/\\\/smitabharat.com\\\/blog\"]}]}<\/script>\n<!-- \/ Yoast SEO plugin. -->","yoast_head_json":{"title":"Go Tree Programs: BST, Traversals, Height, LCA","description":"Go tree programs with output: binary search tree insert, search and delete, four traversals, height, validate BST and LCA, plus tree interview Q&A.","robots":{"index":"index","follow":"follow","max-snippet":"max-snippet:-1","max-image-preview":"max-image-preview:large","max-video-preview":"max-video-preview:-1"},"canonical":"https:\/\/smitabharat.com\/blog\/go-tree-programs\/","og_locale":"en_US","og_type":"article","og_title":"Go Tree Programs: BST, Traversals, Height, LCA","og_description":"Go tree programs with output: binary search tree insert, search and delete, four traversals, height, validate BST and LCA, plus tree interview Q&A.","og_url":"https:\/\/smitabharat.com\/blog\/go-tree-programs\/","og_site_name":"Smita Bharat - Blog","article_published_time":"2026-10-10T09:30:00+00:00","article_modified_time":"2026-11-28T19:59:24+00:00","og_image":[{"width":2400,"height":1260,"url":"https:\/\/smitabharat.com\/blog\/wp-content\/uploads\/2026\/10\/go-tree-programs-featured.png","type":"image\/png"}],"author":"Smita","twitter_card":"summary_large_image","twitter_misc":{"Written by":"Smita","Est. reading time":"24 minutes"},"schema":{"@context":"https:\/\/schema.org","@graph":[{"@type":"Article","@id":"https:\/\/smitabharat.com\/blog\/go-tree-programs\/#article","isPartOf":{"@id":"https:\/\/smitabharat.com\/blog\/go-tree-programs\/"},"author":{"name":"Smita","@id":"https:\/\/smitabharat.com\/blog\/#\/schema\/person\/27a1b1067d396703215c54acedbfd339"},"headline":"Go Tree Programs: Binary Search Tree, Traversals, Height, LCA","datePublished":"2026-10-10T09:30:00+00:00","dateModified":"2026-11-28T19:59:24+00:00","mainEntityOfPage":{"@id":"https:\/\/smitabharat.com\/blog\/go-tree-programs\/"},"wordCount":2015,"publisher":{"@id":"https:\/\/smitabharat.com\/blog\/#\/schema\/person\/27a1b1067d396703215c54acedbfd339"},"image":{"@id":"https:\/\/smitabharat.com\/blog\/go-tree-programs\/#primaryimage"},"thumbnailUrl":"https:\/\/smitabharat.com\/blog\/wp-content\/uploads\/2026\/10\/go-tree-programs-featured.png","keywords":["Beginner","Go Interview Questions","Go Lang","Go Programs","Go Trees"],"articleSection":["Go Programs"],"inLanguage":"en-US"},{"@type":"WebPage","@id":"https:\/\/smitabharat.com\/blog\/go-tree-programs\/","url":"https:\/\/smitabharat.com\/blog\/go-tree-programs\/","name":"Go Tree Programs: BST, Traversals, Height, LCA","isPartOf":{"@id":"https:\/\/smitabharat.com\/blog\/#website"},"primaryImageOfPage":{"@id":"https:\/\/smitabharat.com\/blog\/go-tree-programs\/#primaryimage"},"image":{"@id":"https:\/\/smitabharat.com\/blog\/go-tree-programs\/#primaryimage"},"thumbnailUrl":"https:\/\/smitabharat.com\/blog\/wp-content\/uploads\/2026\/10\/go-tree-programs-featured.png","datePublished":"2026-10-10T09:30:00+00:00","dateModified":"2026-11-28T19:59:24+00:00","description":"Go tree programs with output: binary search tree insert, search and delete, four traversals, height, validate BST and LCA, plus tree interview Q&A.","breadcrumb":{"@id":"https:\/\/smitabharat.com\/blog\/go-tree-programs\/#breadcrumb"},"inLanguage":"en-US","potentialAction":[{"@type":"ReadAction","target":["https:\/\/smitabharat.com\/blog\/go-tree-programs\/"]}]},{"@type":"ImageObject","inLanguage":"en-US","@id":"https:\/\/smitabharat.com\/blog\/go-tree-programs\/#primaryimage","url":"https:\/\/smitabharat.com\/blog\/wp-content\/uploads\/2026\/10\/go-tree-programs-featured.png","contentUrl":"https:\/\/smitabharat.com\/blog\/wp-content\/uploads\/2026\/10\/go-tree-programs-featured.png","width":2400,"height":1260,"caption":"Go Tree Programs featured image: BST traversal and height output"},{"@type":"BreadcrumbList","@id":"https:\/\/smitabharat.com\/blog\/go-tree-programs\/#breadcrumb","itemListElement":[{"@type":"ListItem","position":1,"name":"Home","item":"https:\/\/smitabharat.com\/blog\/"},{"@type":"ListItem","position":2,"name":"Go Tree Programs: Binary Search Tree, Traversals, Height, LCA"}]},{"@type":"WebSite","@id":"https:\/\/smitabharat.com\/blog\/#website","url":"https:\/\/smitabharat.com\/blog\/","name":"Smita Bharat Blog","description":"Golang &amp; Backend Development Tutorials and Interview Questions","publisher":{"@id":"https:\/\/smitabharat.com\/blog\/#\/schema\/person\/27a1b1067d396703215c54acedbfd339"},"alternateName":"Smita Bharat","potentialAction":[{"@type":"SearchAction","target":{"@type":"EntryPoint","urlTemplate":"https:\/\/smitabharat.com\/blog\/?s={search_term_string}"},"query-input":{"@type":"PropertyValueSpecification","valueRequired":true,"valueName":"search_term_string"}}],"inLanguage":"en-US"},{"@type":["Person","Organization"],"@id":"https:\/\/smitabharat.com\/blog\/#\/schema\/person\/27a1b1067d396703215c54acedbfd339","name":"Smita","logo":{"@id":"https:\/\/smitabharat.com\/blog\/#\/schema\/person\/image\/"},"sameAs":["https:\/\/smitabharat.com\/blog"]}]}},"_links":{"self":[{"href":"https:\/\/smitabharat.com\/blog\/wp-json\/wp\/v2\/posts\/854","targetHints":{"allow":["GET"]}}],"collection":[{"href":"https:\/\/smitabharat.com\/blog\/wp-json\/wp\/v2\/posts"}],"about":[{"href":"https:\/\/smitabharat.com\/blog\/wp-json\/wp\/v2\/types\/post"}],"author":[{"embeddable":true,"href":"https:\/\/smitabharat.com\/blog\/wp-json\/wp\/v2\/users\/1"}],"replies":[{"embeddable":true,"href":"https:\/\/smitabharat.com\/blog\/wp-json\/wp\/v2\/comments?post=854"}],"version-history":[{"count":1,"href":"https:\/\/smitabharat.com\/blog\/wp-json\/wp\/v2\/posts\/854\/revisions"}],"predecessor-version":[{"id":902,"href":"https:\/\/smitabharat.com\/blog\/wp-json\/wp\/v2\/posts\/854\/revisions\/902"}],"wp:featuredmedia":[{"embeddable":true,"href":"https:\/\/smitabharat.com\/blog\/wp-json\/wp\/v2\/media\/851"}],"wp:attachment":[{"href":"https:\/\/smitabharat.com\/blog\/wp-json\/wp\/v2\/media?parent=854"}],"wp:term":[{"taxonomy":"category","embeddable":true,"href":"https:\/\/smitabharat.com\/blog\/wp-json\/wp\/v2\/categories?post=854"},{"taxonomy":"post_tag","embeddable":true,"href":"https:\/\/smitabharat.com\/blog\/wp-json\/wp\/v2\/tags?post=854"},{"taxonomy":"swapz_series","embeddable":true,"href":"https:\/\/smitabharat.com\/blog\/wp-json\/wp\/v2\/swapz_series?post=854"}],"curies":[{"name":"wp","href":"https:\/\/api.w.org\/{rel}","templated":true}]}}