0
0
DSA Goprogramming

Binary Tree Node Structure in DSA Go

Choose your learning style9 modes available
Mental Model
A binary tree node holds a value and links to up to two child nodes, left and right.
Analogy: Think of a family tree where each person can have up to two children, one on the left and one on the right.
    [Node]
    /    \
[Left]  [Right]
   ↑       ↑
  left   right
Dry Run Walkthrough
Input: Create a binary tree node with value 10, left child 5, right child 15
Goal: Build a simple binary tree node linking to two children
Step 1: Create root node with value 10
[10] -> left: null, right: null
Why: Start with the main node holding the value
Step 2: Create left child node with value 5 and link to root's left
[10] -> left: [5], right: null
Why: Attach left child to root node
Step 3: Create right child node with value 15 and link to root's right
[10] -> left: [5], right: [15]
Why: Attach right child to root node
Result:
[10] -> left: [5], right: [15]
Annotated Code
DSA Go
package main

import "fmt"

type TreeNode struct {
    Val   int
    Left  *TreeNode
    Right *TreeNode
}

func main() {
    root := &TreeNode{Val: 10}
    root.Left = &TreeNode{Val: 5}
    root.Right = &TreeNode{Val: 15}

    fmt.Printf("%d -> left: %d, right: %d\n", root.Val, root.Left.Val, root.Right.Val)
}
root := &TreeNode{Val: 10}
Create root node with value 10
root.Left = &TreeNode{Val: 5}
Create left child node with value 5 and link to root
root.Right = &TreeNode{Val: 15}
Create right child node with value 15 and link to root
OutputSuccess
10 -> left: 5, right: 15
Complexity Analysis
Time: O(1) because creating and linking nodes is a constant time operation
Space: O(1) for each node created, space grows linearly with number of nodes
vs Alternative: Compared to arrays, binary tree nodes use pointers to link children, allowing flexible structure without fixed size
Edge Cases
Node with no children
Left and right pointers are null, representing leaf node
DSA Go
// if omitted, left is null
root.Left = &TreeNode{Val: 5}
Node with only one child
One pointer is null, the other points to child node
DSA Go
// can be omitted to have only left child
root.Right = &TreeNode{Val: 15}
When to Use This Pattern
When you need to represent hierarchical data with up to two children per item, use binary tree node structure to link values naturally.
Common Mistakes
Mistake: Forgetting to initialize child nodes before linking
Fix: Always create child nodes with &TreeNode{} before assigning to Left or Right
Summary
It defines a node with a value and two pointers to left and right children.
Use it when building trees where each node can have up to two children.
The key is each node links directly to its children, forming a branching structure.