Create Binary Tree From Descriptions

You are given a 2D integer array descriptions where descriptions[i] = [parent, child, isLeft] means parent is the parent of child in a binary tree of unique values. If isLeft == 1, child is the left child of parent; if isLeft == 0, it is the right child. Construct the binary tree described by descriptions and return its root. The test cases guarantee the descriptions form a valid binary tree.

30:00

Create Binary Tree From Descriptions
medium
Free written solution
Topics
Companies

You are given a 2D integer array descriptions where descriptions[i] = [parent, child, isLeft] means parent is the parent of child in a binary tree of unique values. If isLeft == 1, child is the left child of parent; if isLeft == 0, it is the right child. Construct the binary tree described by descriptions and return its root. The test cases guarantee the descriptions form a valid binary tree.

Example 1:
Input: {"descriptions":[[20,15,1],[20,17,0],[50,20,1],[50,80,0],[80,19,1]]}
Output: [50,20,80,15,17,19]
Constraints:
  • 1≤descriptions.length≤1041 \leq \text{descriptions.length} \leq 10^4

  • descriptions[i].length=3\text{descriptions}[i].\text{length} = 3

  • 1≤parenti,childi≤1051 \leq \text{parent}_i, \text{child}_i \leq 10^5

  • 0≤isLefti≤10 \leq \text{isLeft}_i \leq 1

  • The binary tree described by descriptions is valid.

Test Cases
Input (Stdin)
Expected Output (Stdout)
Execution Result

Run code to see results.

Input
arr ={"descriptions":[[20,15,1],[20,17,0],[50,20,1],[50,80,0],[80,19,1]]}

Start with an empty map from value to node and an empty set of values that appear as a child.

descriptions

[20, 15, 1]left
[20, 17, 0]right
[50, 20, 1]left
[50, 80, 0]right
[80, 19, 1]left

children set (0)

empty

left linkright linkthis steproot (never a child)

root = the one value that is never a child

Variables
VariableValue
row-
nodes0
children0
DepthFunction Call
Stack empty
0/15