Bird
Raised Fist0
DSA Goprogramming~20 mins

Serialize and Deserialize Binary Tree in DSA Go - Practice Problems & Challenges

Choose your learning style10 modes available
Challenge - 5 Problems
🎖️
Binary Tree Serialization Master
Get all challenges correct to earn this badge!
Test your skills under time pressure!
❓ Predict Output
intermediate
2:00remaining
Output of Serialization with Preorder Traversal
What is the output of the serialization function when applied to this binary tree?

Tree structure:
1
/ \
2 3
/ \
4 5

The serialization uses preorder traversal with '#' for null nodes and commas as separators.
DSA Go
type TreeNode struct {
    Val   int
    Left  *TreeNode
    Right *TreeNode
}

func serialize(root *TreeNode) string {
    if root == nil {
        return "#"
    }
    leftSerialized := serialize(root.Left)
    rightSerialized := serialize(root.Right)
    return fmt.Sprintf("%d,%s,%s", root.Val, leftSerialized, rightSerialized)
}

// Tree construction
root := &TreeNode{1, &TreeNode{2, nil, nil}, &TreeNode{3, &TreeNode{4, nil, nil}, &TreeNode{5, nil, nil}}}

fmt.Println(serialize(root))
A1,2,#,#,3,4,#,#,5,#,#
B1,2,#,#,3,4,#,#,5,#
C1,2,#,3,4,#,#,5,#,#
D1,2,#,#,3,4,#,5,#,#,#
Attempts:
2 left
💡 Hint
Remember preorder traversal visits root, then left subtree, then right subtree. Null children are marked with '#'.
❓ Predict Output
intermediate
2:00remaining
Result of Deserializing a Serialized String
Given the serialized string "1,2,#,#,3,#,4,#,#", what is the value of the right child of the root after deserialization?
DSA Go
type TreeNode struct {
    Val   int
    Left  *TreeNode
    Right *TreeNode
}

func deserialize(data string) *TreeNode {
    vals := strings.Split(data, ",")
    var index int
    var build func() *TreeNode
    build = func() *TreeNode {
        if vals[index] == "#" {
            index++
            return nil
        }
        val, _ := strconv.Atoi(vals[index])
        index++
        node := &TreeNode{Val: val}
        node.Left = build()
        node.Right = build()
        return node
    }
    return build()
}

root := deserialize("1,2,#,#,3,#,4,#,#")
fmt.Println(root.Right.Val)
A0
B4
C3
Dnil (no right child)
Attempts:
2 left
💡 Hint
Trace the deserialization step by step, matching preorder nodes and nulls.
🧠 Conceptual
advanced
1:30remaining
Understanding Null Markers in Serialization
Why is it necessary to include a special marker (like '#') for null nodes when serializing a binary tree using preorder traversal?
ATo indicate the end of the serialized string
BTo distinguish between left and right children during deserialization
CTo reduce the size of the serialized string
DTo mark nodes that have only one child
Attempts:
2 left
💡 Hint
Think about how the deserialization function knows when to stop building a subtree.
❓ Predict Output
advanced
2:00remaining
Output of Deserialization Followed by Serialization
What is the output of serializing the tree obtained by deserializing the string "1,#,2,#,3,#,#" using the given serialize and deserialize functions?
DSA Go
type TreeNode struct {
    Val   int
    Left  *TreeNode
    Right *TreeNode
}

func serialize(root *TreeNode) string {
    if root == nil {
        return "#"
    }
    leftSerialized := serialize(root.Left)
    rightSerialized := serialize(root.Right)
    return fmt.Sprintf("%d,%s,%s", root.Val, leftSerialized, rightSerialized)
}

func deserialize(data string) *TreeNode {
    vals := strings.Split(data, ",")
    var index int
    var build func() *TreeNode
    build = func() *TreeNode {
        if vals[index] == "#" {
            index++
            return nil
        }
        val, _ := strconv.Atoi(vals[index])
        index++
        node := &TreeNode{Val: val}
        node.Left = build()
        node.Right = build()
        return node
    }
    return build()
}

root := deserialize("1,#,2,#,3,#,#")
fmt.Println(serialize(root))
A1,#,2,#,#
B1,#,2,#,3,#
C1,#,2,#,3,#,#,#
D1,#,2,#,3,#,#
Attempts:
2 left
💡 Hint
The deserialized tree is skewed to the right. Serialization should reproduce the same string.
🚀 Application
expert
2:30remaining
Count Nodes from Serialized String Without Full Deserialization
Given a serialized binary tree string using preorder traversal with '#' for nulls, which approach correctly counts the total number of non-null nodes without building the tree?
AUse a stack to simulate preorder traversal, increment count for each number, and skip '#' markers
BCount all values that are not '#' by splitting the string by commas
CCount the number of commas and subtract the number of '#' markers
DTraverse the string and increment count only when a number is followed by two '#' markers
Attempts:
2 left
💡 Hint
Think about how preorder traversal works and how nulls affect node counting.

Practice

(1/5)
1. What is the main purpose of serialize and deserialize functions for a binary tree?
easy
A. Convert a binary tree into a string and back to a tree
B. Sort the nodes of a binary tree in ascending order
C. Calculate the height of a binary tree
D. Delete all nodes in a binary tree

Solution

  1. Step 1: Understand serialization

    Serialization means converting a binary tree into a string format so it can be stored or sent.
  2. Step 2: Understand deserialization

    Deserialization means converting the string back into the original binary tree structure.
  3. Final Answer:

    Convert a binary tree into a string and back to a tree -> Option A
  4. Quick Check:

    Serialize/Deserialize = Convert tree to string and back [OK]
Hint: Serialization means tree to string, deserialization reverses it [OK]
Common Mistakes:
  • Confusing serialization with sorting
  • Thinking serialization deletes nodes
  • Mixing serialization with tree height calculation
2. Which of the following Go function signatures correctly represents a deserialize function for a binary tree?
easy
A. func deserialize(root *TreeNode) string
B. func deserialize(data int) *TreeNode
C. func deserialize(data string) *TreeNode
D. func deserialize(data []int) int

Solution

  1. Step 1: Identify input and output types

    Deserialize takes a string (serialized data) and returns a pointer to the root node of the tree.
  2. Step 2: Match function signature

    func deserialize(data string) *TreeNode matches this: input is string, output is *TreeNode pointer.
  3. Final Answer:

    func deserialize(data string) *TreeNode -> Option C
  4. Quick Check:

    Deserialize input string, output tree node pointer [OK]
Hint: Deserialize input is string, output is tree root pointer [OK]
Common Mistakes:
  • Using int instead of string as input
  • Returning string instead of tree node
  • Confusing serialize and deserialize signatures
3. Given the following serialized string of a binary tree using preorder with '#' as null marker: "1,2,#,#,3,4,#,#,5,#,#", what is the inorder traversal output of the deserialized tree?
medium
A. [1, 3, 2, 4, 5]
B. [1, 2, 3, 4, 5]
C. [2, 4, 1, 3, 5]
D. [2, 1, 4, 3, 5]

Solution

  1. Step 1: Reconstruct tree from preorder string

    Preorder: 1 (root), 2 (left child), # (left null), # (right null), 3 (right child), 4 (left), #, #, 5 (right), #, #.
  2. Step 2: Draw tree and find inorder traversal

    Tree structure:
    1
    / \
    2 3
    / \
    4 5
    Inorder (left, root, right): 2, 1, 4, 3, 5
  3. Final Answer:

    [2, 1, 4, 3, 5] -> Option D
  4. Quick Check:

    Inorder traversal = [2,1,4,3,5] [OK]
Hint: Draw tree from preorder, then do left-root-right for inorder [OK]
Common Mistakes:
  • Mixing preorder and inorder traversal orders
  • Ignoring null markers '#' in deserialization
  • Incorrectly placing children nodes
4. Consider this Go code snippet for deserializing a binary tree. What is the bug?
func deserialize(data string) *TreeNode {
    vals := strings.Split(data, ",")
    var index int
    var build func() *TreeNode
    build = func() *TreeNode {
        if vals[index] == "#" {
            index++
            return nil
        }
        node := &TreeNode{Val: vals[index]}
        index++
        node.Left = build()
        node.Right = build()
        return node
    }
    return build()
}
medium
A. TreeNode.Val should be converted from string to int
B. Index variable should be global, not local
C. Strings.Split should use space instead of comma
D. The build function should not be recursive

Solution

  1. Step 1: Check TreeNode.Val assignment

    vals[index] is a string, but TreeNode.Val expects an int. Conversion is missing.
  2. Step 2: Identify fix

    Use strconv.Atoi(vals[index]) to convert string to int before assigning.
  3. Final Answer:

    TreeNode.Val should be converted from string to int -> Option A
  4. Quick Check:

    String to int conversion missing [OK]
Hint: Convert string to int before assigning to node value [OK]
Common Mistakes:
  • Forgetting to convert string to int
  • Changing index scope unnecessarily
  • Misusing Split delimiter
5. You want to serialize a binary tree so that it can be stored and later deserialized exactly as it was. Which approach best handles trees with duplicate values and null nodes?
hard
A. Use inorder traversal without null markers
B. Use preorder traversal with a special marker for null nodes
C. Use postorder traversal ignoring null nodes
D. Store only node values in a list without structure

Solution

  1. Step 1: Understand serialization needs

    To reconstruct the exact tree, we must record node order and null positions.
  2. Step 2: Evaluate options

    Preorder with null markers records structure and values including duplicates. Inorder or postorder without nulls loses structure. Storing only values loses tree shape.
  3. Final Answer:

    Use preorder traversal with a special marker for null nodes -> Option B
  4. Quick Check:

    Preorder + null markers preserves structure and duplicates [OK]
Hint: Preorder + null markers saves full tree structure [OK]
Common Mistakes:
  • Ignoring null nodes in serialization
  • Using inorder without nulls loses tree shape
  • Assuming values alone define tree
Recommended

Ready to prove it?

Pass the test and this pattern moves unknown strong while earning +1 Grip toward your certificate.

10 questions~5 mineasy hard