Leetcode 2196: Create Binary Tree From Descriptions

grid47
grid47
Exploring patterns and algorithms
Apr 1, 2024 7 min read

You are given a list of triplets representing the structure of a binary tree. Each triplet [parent, child, isLeft] indicates that parent is the parent of child, and if isLeft is 1, child is the left child of parent, otherwise, it’s the right child. Your task is to reconstruct the binary tree and return the root node.
Problem
Approach
Steps
Complexity
Input: The input consists of a list of triplets where each triplet represents a parent-child relationship in a binary tree. The structure of the input is: `[parent, child, isLeft]`. The list contains information about all nodes of the tree.
Example: descriptions = [[10, 5, 1], [10, 20, 0], [5, 3, 1], [3, 2, 0]]
Constraints:
• 1 <= descriptions.length <= 10^4
• descriptions[i].length == 3
• 1 <= parent, child <= 10^5
• 0 <= isLeft <= 1
• The binary tree described by descriptions is valid.
Output: The output should be the root node of the reconstructed binary tree, represented as a binary tree node. The output should be in the form of an array representation of the tree starting from the root.
Example: [10, 5, 20, 3, 2]
Constraints:
• The output should represent the tree starting from the root node.
Goal: The goal is to reconstruct the binary tree from the descriptions and return its root node.
Steps:
• 1. Parse the descriptions to identify the root node (the node that does not have any parent).
• 2. Create a map to store the nodes as we build the tree.
• 3. For each triplet, connect the parent and child nodes as left or right based on the value of `isLeft`.
• 4. Return the root node once the tree is fully constructed.
Goal: Ensure that the input list is well-formed and the tree is valid.
Steps:
• The binary tree described by descriptions is valid and does not contain any cycles.
Assumptions:
• The binary tree is guaranteed to be valid and can always be constructed from the descriptions.
Input: descriptions = [[10, 5, 1], [10, 20, 0], [5, 3, 1], [3, 2, 0]]
Explanation: In this example, we construct the binary tree where 10 is the root, 5 is the left child of 10, 20 is the right child of 10, 3 is the left child of 5, and 2 is the right child of 3.

Input: descriptions = [[1, 2, 1], [2, 3, 0], [3, 4, 1]]
Explanation: In this example, the tree is constructed such that 1 is the root, 2 is the left child of 1, 3 is the right child of 2, and 4 is the left child of 3.

Link to LeetCode Lab


LeetCode Solutions Library / DSA Sheets / Course Catalog
comments powered by Disqus