Create Binary Tree From Descriptions - Problem

You are given a 2D integer array descriptions where descriptions[i] = [parenti, childi, isLefti] indicates that parenti is the parent of childi in a binary tree of unique values.

Furthermore:

  • If isLefti == 1, then childi is the left child of parenti.
  • If isLefti == 0, then childi is the right child of parenti.

Construct the binary tree described by descriptions and return its root.

The test cases will be generated such that the binary tree is valid.

Input & Output

Example 1 — Basic Tree
$ Input: descriptions = [[20,15,1],[20,17,0],[50,20,1],[50,80,0],[80,19,1]]
Output: [50,20,80,15,17,19]
💡 Note: Root is 50. Left child 20 has children 15 (left) and 17 (right). Right child 80 has left child 19.
Example 2 — Simple Tree
$ Input: descriptions = [[1,2,1],[1,3,0],[2,4,1],[2,5,0]]
Output: [1,2,3,4,5]
💡 Note: Root is 1. Left child is 2 with children 4 and 5. Right child is 3.
Example 3 — Single Root
$ Input: descriptions = [[39,70,1]]
Output: [39,70]
💡 Note: Simple tree with root 39 and single left child 70.

Constraints

  • 1 ≤ descriptions.length ≤ 104
  • descriptions[i].length == 3
  • 1 ≤ parenti, childi ≤ 105
  • isLefti is either 0 or 1
  • The binary tree described by descriptions is valid

Visualization

Tap to expand
Create Binary Tree From DescriptionsInput: Relationships[20,15,1] → 15 is left of 20[20,17,0] → 17 is right of 20[50,20,1] → 20 is left of 50[50,80,0] → 80 is right of 50[80,19,1] → 19 is left of 80Process: Build TreeCreate nodes in hash mapConnect parent-child linksTrack children: {15,17,20,80,19}Root = node NOT in childrenRoot = 50Output: Binary Tree502080151719Result: [50,20,80,15,17,19]
Understanding the Visualization
1
Input
Array of [parent, child, isLeft] relationships
2
Process
Build nodes and connect parent-child links
3
Output
Binary tree with identified root node
Key Takeaway
🎯 Key Insight: The root is the only node value that never appears as a child in any relationship description
Asked in
Microsoft 35 Amazon 28 Facebook 22 Google 18
28.4K Views
Medium Frequency
~15 min Avg. Time
892 Likes
Ln 1, Col 1
Smart Actions
💡 Explanation
AI Ready
💡 Suggestion Tab to accept Esc to dismiss
// Output will appear here after running code
Code Editor Closed
Click the red button to reopen