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 Descriptions INPUT descriptions array: [20, 15, 1] - 20's left child [20, 17, 0] - 20's right child [50, 20, 1] - 50's left child [50, 80, 0] - 50's right child [80, 19, 1] - 80's left child Format: [parent, child, isLeft] isLeft: 1=left, 0=right Relationships: 50 --> 20 (L) 50 --> 80 (R) 20 --> 15 (L) 20 --> 17 (R) 80 --> 19 (L) Input Values: 15, 17, 19, 20, 50, 80 ALGORITHM STEPS 1 Build Node Map Store all nodes in HashMap nodeMap: {15, 17, 19, 20, 50, 80} Key: value, Value: TreeNode 2 Track Children Mark nodes that are children childSet: {15, 17, 19, 20, 80} 3 Connect Parent-Child Set left/right based on isLeft if isLeft==1: parent.left = child if isLeft==0: parent.right = child 4 Find Root Root is NOT in childSet 50 NOT in childSet --> ROOT! FINAL RESULT Constructed Binary Tree: 50 20 80 15 17 19 L R L R L ROOT Output (Level Order): [50, 20, 80, 15, 17, 19] OK - Tree Built! Time: O(n) | Space: O(n) Key Insight: Use a HashMap to store nodes by value for O(1) lookup when building parent-child relationships. The root is the only node that never appears as a child in any description - track children in a Set to find it efficiently. This approach processes all relationships in a single pass through the array. TutorialsPoint - Create Binary Tree From Descriptions | Hash Map Optimization
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