Create Binary Tree From Descriptions

Medium Topics Company Tags

You are given a list of parent-child relationships for a binary tree whose node values are unique. Each entry [parent, child, isLeft] places child under parent: isLeft = 1 means the left child, and isLeft = 0 means the right child.

The entries may appear in any order and together describe one valid binary tree. Construct this tree and return its root.

The output examples use level-order traversal, with null for missing children and trailing nulls omitted.

Example 1:

Create Binary Tree From Descriptions, example 1: illustration of the example

Input: descriptions = [[6,3,1],[10,6,0],[6,8,0]]

Output: [10,null,6,3,8]

Explanation: Value 10 never appears as a child, so it is the root. Its right child is 6; node 6 has left child 3 and right child 8. The first null marks the missing left child of 10.

Example 2:

Create Binary Tree From Descriptions, example 2: illustration of the example

Input: descriptions = [[4,7,0]]

Output: [4,null,7]

Explanation: Node 4 is the root and has only a right child, 7. The missing left child is represented by null.

Example 3:

Create Binary Tree From Descriptions, example 3: illustration of the example

Input: descriptions = [[30,10,1],[10,20,0],[20,15,1]]

Output: [30,10,null,null,20,15]

Explanation: The relationships form a chain: 30 has left child 10, node 10 has right child 20, and node 20 has left child 15. Nulls preserve these left and right positions in level order.

Constraints:

  • 1 <= descriptions.length <= 10^4
  • descriptions[i].length == 3
  • 1 <= parent, child <= 10^5
  • isLeft is either 0 or 1.
  • Node values are unique, and the descriptions form one valid binary tree.


Topics

Company Tags

Please upgrade to NeetCode Pro to view company tags.