Katkat

Build a Binary Tree from Descriptions

ByteDanceSoftware Engineer · Technical Screen

Last updated

This problem tests tree traversal, hash map utilization for parent-child relationship tracking, and identification of the root node in a graph-based structure.

Problem Statement

You are given a 2D array descriptions where each descriptions[i] = [parent, child, isLeft] indicates that parent is the parent of child. If isLeft == 1, then child is the left child of parent; otherwise, child is the right child.

Construct the binary tree and return the root node of the resulting tree.

It is guaranteed that the tree is valid, has no cycles, and the root node is unique.

Function Signature

class TreeNode:
    def __init__(self, val=0, left=None, right=None):
        self.val = val
        self.left = left
        self.right = right

def createBinaryTree(descriptions: list[list[int]]) -> TreeNode:

Examples

Example 1: Input: descriptions = [[20,15,1],[20,17,0],[50,20,1],[50,80,0]] Output: A tree with root 50, where 50 has children 20 (left) and 80 (right), 20 has children 15 (left) and 17 (right).

Example 2: Input: descriptions = [[1,2,1],[2,3,0],[3,4,1]] Output: A tree structure where 1 -> 2 (left) -> 3 (right) -> 4 (left).

Constraints

  • 1 <= descriptions.length <= 10^4
  • 1 <= parent, child <= 10^5
  • isLeft is either 0 or 1.

Edge Cases

  • A single-node tree or a skewed tree (all nodes only have one child).
  • Ensuring the root is the node that never appears as a child in the input array.

Hints

Hint 1

Use a hash map to keep track of created TreeNode objects to avoid duplicate instances of the same value.

Hint 2

Use a set to store all nodes that appear as children; the node that is a parent but never appears in the child set must be the root.

Hint 3

Iterate through the descriptions once to populate the map and identify children, then link the nodes using the parent-child relationships defined.

Follow-up questions

  • What is the time and space complexity of your solution? Can you optimize space if the node values were limited to a small range?
  • How would you modify the algorithm if the input could contain cycles, and how would you detect them?
  • If the tree were extremely large (exceeding memory limits), how might you approach this differently?