Create Binary Tree From Descriptions — LeetCode 2196 Python Solution

MediumTreeArrayHash TableBinary Tree
Problem
#2196
Reading time
4 min

The problem

You are given a 2D integer array descriptions where descriptions[i] = [parenti, childi, isLefti] indicates that parenti is the parent of childi in a binary tree of unique values. Furthermore, If isLefti == 1, then childi is the left child of parenti.

Example

Input
descriptions = [[20,15,1],[20,17,0],[50,20,1],[50,80,0],[80,19,1]]
Output
[50,20,80,15,17,19]
Explanation
The root node is the node with value 50 since it has no parent.

Python solution

Python
# Definition for a binary tree node.
# class TreeNode:
#     def __init__(self, val=0, left=None, right=None):
#         self.val = val
#         self.left = left
#         self.right = right
class Solution:
    def createBinaryTree(self, descriptions: List[List[int]]) -> Optional[TreeNode]:
        nodes = defaultdict(TreeNode)
        children = set()
        for parent, child, isLeft in descriptions:
            if parent not in nodes:
                nodes[parent] = TreeNode(parent)
            if child not in nodes:
                nodes[child] = TreeNode(child)
            children.add(child)
            if isLeft:
                nodes[parent].left = nodes[child]
            else:
                nodes[parent].right = nodes[child]
        root = (set(nodes.keys()) - children).pop()
        return nodes[root]

Complexity

MeasureComplexity
TimeO(n)
SpaceO(n), where n is the length of \textit{descriptions} auxiliary

Pattern: Tree Traversal

Choose the order — preorder, inorder, postorder, level — and the problem solves itself. LeetCode 2196. Create Binary Tree From Descriptions is filed here because LeetCode tags it Tree and Binary Tree, which is the vocabulary this hub collects.

The tree traversal guide has the Python template for the pattern and the 225 LeetCode problems that use it.

Related problems

Frequently asked questions

How hard is LeetCode 2196. Create Binary Tree From Descriptions?
LeetCode 2196. Create Binary Tree From Descriptions is rated Medium on LeetCode.
What is the time complexity of LeetCode 2196. Create Binary Tree From Descriptions?
The Python solution on this page runs in O(n).
What is the space complexity of LeetCode 2196. Create Binary Tree From Descriptions?
The Python solution on this page uses O(n), where n is the length of \textit{descriptions} auxiliary space.
What topics does LeetCode 2196. Create Binary Tree From Descriptions cover?
LeetCode 2196. Create Binary Tree From Descriptions is tagged Tree, Array, Hash Table and Binary Tree on LeetCode.

Stuck on problems like this in a live interview?

Stealth Interview is a desktop app for macOS and Windows. It reads the problem off your screen and returns a working solution with a step-by-step explanation and its time and space complexity — invisible to screen sharing.

Get Stealth Interview