Create Binary Tree From Descriptions (LeetCode 2196): Solution and Explanation

Medium
Array
Hash Table
Tree
Binary Tree

Each row [parent, child, isLeft] gives one edge of a binary tree with unique values. Build the tree and return its root.

Intuition

The rows arrive in any order, so a child can be mentioned before its parent has a parent of its own. That rules out building top down from the root. Instead, treat every value as a node that exists from the first time it is mentioned, and wire edges as they come.

A hash map from value to node makes this easy: look up or create both ends of a row, then set the parent's left or right pointer. After the last row every edge is in place, even though the pieces were assembled out of order.

Finding the root is the only remaining question. Every node except the root has exactly one parent, so it appears as a child in exactly one row. The root never does. Record every child value in a set, then pick the value that is not in it.

Approach: Value-to-node map with a children set

  1. Create an empty map nodes (value to TreeNode) and an empty set children.
  2. For each row [parent, child, isLeft], create a node for parent and for child if the map does not have one yet.
  3. Set nodes[parent].left = nodes[child] when isLeft is 1, otherwise nodes[parent].right = nodes[child].
  4. Add child to children.
  5. Return the node whose value is not in children.

Step-by-step example

descriptions = [[20,15,1],[20,17,0],[50,20,1],[50,80,0],[80,19,1]]
  1. Row [20,15,1]: create 20 and 15, link 15 as the left child of 20. children = {15}.
  2. Row [20,17,0]: create 17, link it as the right child of 20. children = {15, 17}.
  3. Row [50,20,1]: create 50 and reuse 20, so the whole 20 subtree now hangs to the left of 50. children = {15, 17, 20}.
  4. Rows [50,80,0] and [80,19,1]: create 80 and 19 and link them. children = {15, 17, 20, 80, 19}.
  5. Scan the map: 20, 15 and 17 are children, 50 is not. Return 50, which reads [50,20,80,15,17,19] level by level.

Code: Python, Java, C++

1class Solution:
2    def createBinaryTree(self, descriptions: List[List[int]]) -> Optional[TreeNode]:
3        nodes = {}
4        children = set()
5        for parent, child, is_left in descriptions:
6            if parent not in nodes:
7                nodes[parent] = TreeNode(parent)
8            if child not in nodes:
9                nodes[child] = TreeNode(child)
10            if is_left:
11                nodes[parent].left = nodes[child]
12            else:
13                nodes[parent].right = nodes[child]
14            children.add(child)
15        for val, node in nodes.items():
16            if val not in children:
17                return node
18        return None
Press play on the visualizer and the running line lights up here.

Time and space complexity

Time

O(n)

Each row does a constant number of hash lookups and pointer writes, and the final scan is linear in the number of nodes, which is n + 1.

Space

O(n)

The map holds one node per value and the set holds one entry per child.

Other approaches

Track parent pointers instead of a set (time O(n), space O(n))

Store parentOf[child] = parent while linking, then start from any value and climb parentOf until there is no parent. Same cost, and it finds the root without scanning every node.

Sum trick (time O(n), space O(n))

Because every non-root value appears exactly once as a child, the root is (sum of distinct values) minus (sum of child values). It avoids the set but still needs the map to build the nodes.

Common mistakes

  • Creating a fresh node every time a value is mentioned. A value can be a child in one row and a parent in several others; they must all share one node or the subtrees disconnect.
  • Assuming the first row's parent is the root. Rows come in any order, and the root can appear last.
  • Treating isLeft as a boolean in a language where 0 and 1 are not booleans. Compare it to 1 explicitly.

Frequently asked questions

Why is exactly one value missing from the children set?

A tree with m nodes has m - 1 edges, and each edge gives one distinct child. So m - 1 of the m values are children and the remaining one, the root, is not.

Does the order of the rows matter?

No. The map lets a node exist before its parent is known, so links made early stay valid when the parent is attached later.

How is the answer checked?

The returned root is serialized in level order with null for missing children and trailing nulls trimmed, the same format the input trees use in other problems.