Problem List

Create Binary Tree From Descriptions

May 30, 2025Go array, hash table, tree, binary treemedium

Problem

Approach

Edge Cases

Reflections

Honestly, I like this solution. Even though it TLE’d on the last test case, it passed 84/85 and reads cleanly.

The main reason it’s slow is because it re-scans the entire array for every node recursively, which ends up O(n^2). That’s brutal on big inputs.

Still, the logic is super clear: find the root first, then recurse through the relationships.

I’ll come back and optimize this later with a map-based approach, but for now I’m happy with the logic as-is.

Go Solution
func createBinaryTree(descriptions [][]int) *TreeNode {
    d := descriptions
    possibleRoots := make(map[int]bool)

    for i := 0; i < len(d); i++ {
        if _, found := possibleRoots[d[i][0]]; !found {
            possibleRoots[d[i][0]] = true
        }
        possibleRoots[d[i][1]] = false
    }

    head := &TreeNode{Val:0}
    for key, val := range possibleRoots {
        if val {
            head.Val = key
        }
    }
    head = buildTree(d, head)

    return head
}

func buildTree(d [][]int, head *TreeNode) *TreeNode{
    if head == nil {
        return nil
    }

    for i := 0; i < len(d); i++ {
        if d[i][0] == head.Val {
            head = insertVal(head, d[i])
        }
    }

    head.Left = buildTree(d, head.Left)
    head.Right = buildTree(d, head.Right)

    return head
}

func insertVal(head *TreeNode, description []int) *TreeNode {
    if description[2] == 1 {
        head.Left = &TreeNode{Val:description[1]}
    } else {
        head.Right = &TreeNode{Val:description[1]}
    }

    return head
}
LeetCode Problem Link