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, thenchildiis the left child ofparenti. - If
isLefti == 0, thenchildiis the right child ofparenti.
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
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
💡
Explanation
AI Ready
💡 Suggestion
Tab
to accept
Esc
to dismiss
// Output will appear here after running code