Create Binary Tree From Descriptions - Map & Set

Description

Solution: Map & Set

Use a map 'nodes' to store the references to the tree nodes.
Use a set 'children' to store the values of all children nodes.
This is used to find the root, the root node is the only node that does not exist in the set.

Time Complexity: O(n) 510ms
Space Complexity: O(n) 88.8MB

var createBinaryTree = function(descriptions) {
  let nodes = new Map(), children = new Set();
  for (let [parent, child, isLeft] of descriptions) {
    let parentNode = nodes.get(parent) || new TreeNode(parent);
    if (!nodes.has(parent)) nodes.set(parent, parentNode);
    
    let childNode = nodes.get(child) || new TreeNode(child);
    if (!nodes.has(child)) nodes.set(child, childNode);
    
    if (isLeft) parentNode.left = childNode;
    else parentNode.right = childNode;
    
    children.add(child);
  }

  for (let [parent, child, isLeft] of descriptions) {
    // a node with no parent is the root
    if (!children.has(parent)) return nodes.get(parent);
  }
};

javascript

Comments

Popular posts from this blog

Minimum Number of Operations to Sort a Binary Tree by Level - BFS & Cycle Counting Explained [JS]

Beautiful Towers II - Monotonic Increasing Stack [JS]

Reschedule Meetings for Maximum Free Time I - Sliding Window - Constant Space [JS]

Maximum Sum of Distinct Subarrays With Length K - Sliding Window w/ Two Pointers & Set [JS]

Sum of Prefix Scores of Strings - Trie [JS]