Skip to main content
Back to problems
#2196
Medium Algorithms

Create binary tree from descriptions

Array Hash Table Tree Binary Tree
81.7% acceptance
Feb 25, 2026
1657
39
You are given a 2D integer array descriptions where descriptions[i] = [parenti, childi, isLefti]. If isLefti == 1, childi is the left child of parenti. If isLefti == 0, it's the right child. Construct the binary tree and return its root.

Solution

Rust
Time O(n)
Space O(n)
LeetCode
solution.rs
use std::rc::Rc;
use std::cell::RefCell;
impl Solution {
  pub fn create_binary_tree(descriptions: Vec<Vec<i32>>) -> Option<Rc<RefCell<TreeNode>>> {
    use std::collections::{HashMap, HashSet};
    let mut nodes: HashMap<i32, Rc<RefCell<TreeNode>>> = HashMap::new();
    let mut has_parent: HashSet<i32> = HashSet::new();
    for d in &descriptions {
      let (parent, child, is_left) = (d[0], d[1], d[2]);
      has_parent.insert(child);
      let pnode = nodes.entry(parent)
        .or_insert_with(|| Rc::new(RefCell::new(TreeNode::new(parent))))
        .clone();
      let cnode = nodes.entry(child)
        .or_insert_with(|| Rc::new(RefCell::new(TreeNode::new(child))))
        .clone();
      if is_left == 1 {
        pnode.borrow_mut().left = Some(cnode);
      } else {
        pnode.borrow_mut().right = Some(cnode);
      }
    }
    nodes.iter()
      .find(|(k, _)| !has_parent.contains(k))
      .map(|(_, v)| v.clone())
  }
}