Problem Description
Given a list of descriptions, where each description is an array [parent, child, isLeft] representing that the parent node has a child node, determine whether that child is a left child (if isLeft is 1) or a right child (if isLeft is 0). The tree is guaranteed to be valid and all nodes have distinct values. The goal is to construct the binary tree and return its root.
Key Insights
- Each description provides a parent-child relationship information.
- The tree nodes are unique; therefore, we can use a hash table (or map) to record node values to node instances.
- The root node is the only node that never appears as a child in any description.
- By iterating over the descriptions, we can construct the tree by attaching each child to its corresponding parent's left or right pointer as indicated by isLeft.
Space and Time Complexity
Time Complexity: O(n) where n is the number of descriptions, since we process each description once. Space Complexity: O(n) for storing the mapping of node values to nodes and the set of child nodes.
Solution
We use a hash table (or dictionary/map) to store nodes, ensuring that each node is created only once. Another set is used to keep track of all nodes that appear as a child. After processing every description, the root of the tree will be the node that does not appear in the child set. This approach ensures an efficient, one-pass solution to constructing the tree.