Problem statement

https://leetcode.com/problems/create-binary-tree-from-descriptions/

Solution

Let us create graph G in the form of defaultdict first. Also keep parent for each node. Then use dfs, where we start from root.

Complexity

It is O(n) for time and space.

Code

class Solution:
    def createBinaryTree(self, D):
        G = defaultdict(list)
        par = {}
        for p, c, l in D:
            G[p] += [(c, l)]
            par[c] = p
            
        for x in G:
            if x not in par:
                root = x
            
        def dfs(node):
            ans = TreeNode(node)
            for child, l in G[node]:
                if l == 1:
                    ans.left = dfs(child)
                if l == 0:
                    ans.right = dfs(child)
            return ans
            
            
        return dfs(root)