Create Binary Tree From Descriptions

medium tree array hash map binary tree

Problem

Each description is [parent, child, isLeft]. Build the binary tree and return its root.

Inputdescriptions = [[20,15,1],[20,17,0],[50,20,1],[50,80,0],[80,19,1]]
Outputroot with value 50
50 is the only value never appearing as a child.

def create_binary_tree(descriptions):
    nodes = {}
    is_child = set()
    for p, c, left in descriptions:
        if p not in nodes: nodes[p] = TreeNode(p)
        if c not in nodes: nodes[c] = TreeNode(c)
        if left:
            nodes[p].left = nodes[c]
        else:
            nodes[p].right = nodes[c]
        is_child.add(c)
    for v in nodes:
        if v not in is_child:
            return nodes[v]
    return None
function createBinaryTree(descriptions) {
  const nodes = new Map();
  const isChild = new Set();
  for (const [p, c, left] of descriptions) {
    if (!nodes.has(p)) nodes.set(p, { val: p, left: null, right: null });
    if (!nodes.has(c)) nodes.set(c, { val: c, left: null, right: null });
    if (left) nodes.get(p).left = nodes.get(c);
    else nodes.get(p).right = nodes.get(c);
    isChild.add(c);
  }
  for (const [v, node] of nodes) {
    if (!isChild.has(v)) return node;
  }
  return null;
}
class Solution {
    public TreeNode createBinaryTree(int[][] descriptions) {
        java.util.Map<Integer, TreeNode> nodes = new java.util.HashMap<>();
        java.util.Set<Integer> isChild = new java.util.HashSet<>();
        for (int[] d : descriptions) {
            int p = d[0], c = d[1];
            nodes.putIfAbsent(p, new TreeNode(p));
            nodes.putIfAbsent(c, new TreeNode(c));
            if (d[2] == 1) nodes.get(p).left = nodes.get(c);
            else nodes.get(p).right = nodes.get(c);
            isChild.add(c);
        }
        for (int v : nodes.keySet()) {
            if (!isChild.contains(v)) return nodes.get(v);
        }
        return null;
    }
}
TreeNode* createBinaryTree(vector<vector<int>>& descriptions) {
    unordered_map<int, TreeNode*> nodes;
    unordered_set<int> isChild;
    for (auto& d : descriptions) {
        int p = d[0], c = d[1];
        if (!nodes.count(p)) nodes[p] = new TreeNode(p);
        if (!nodes.count(c)) nodes[c] = new TreeNode(c);
        if (d[2] == 1) nodes[p]->left = nodes[c];
        else nodes[p]->right = nodes[c];
        isChild.insert(c);
    }
    for (auto& [v, node] : nodes) {
        if (!isChild.count(v)) return node;
    }
    return nullptr;
}
Time: O(n) Space: O(n)