LeetCode 2196: Create Binary Tree From Descriptions Solution

Master LeetCode problem 2196 (Create Binary Tree From Descriptions), a medium challenge, with our optimized solutions in Java, C++, and Python. Explore detailed explanations, test your code in our interactive editor, and prepare for coding interviews.

2196. Create Binary Tree From Descriptions

Problem Explanation

Explanation:

To create a binary tree from the given descriptions, we can follow these steps:

  1. Create a hashmap to store the mapping of parent to its corresponding node.
  2. Iterate through the descriptions and create nodes for each child. Connect the child nodes to their respective parent nodes based on the isLeft value.
  3. Return the root node of the binary tree.

Time Complexity:

The time complexity of this approach is O(n) where n is the number of descriptions.

Space Complexity:

The space complexity of this approach is also O(n) due to the hashmap used to store nodes.

:

Solution Code

import java.util.*;

class TreeNode {
    int val;
    TreeNode left;
    TreeNode right;

    TreeNode(int val) {
        this.val = val;
    }
}

public class Solution {
    public TreeNode createBinaryTreeFromDescriptions(int[][] descriptions) {
        Map<Integer, TreeNode> map = new HashMap<>();

        for (int[] desc : descriptions) {
            TreeNode parent = map.computeIfAbsent(desc[0], TreeNode::new);
            TreeNode child = map.computeIfAbsent(desc[1], TreeNode::new);

            if (desc[2] == 1) {
                parent.left = child;
            } else {
                parent.right = child;
            }
        }

        return map.values().stream().filter(node -> node.left == null && node.right == null).findFirst().orElse(null);
    }
}

Try It Yourself

Loading code editor...

Related LeetCode Problems

Frequently Asked Questions

How to solve LeetCode 2196 (Create Binary Tree From Descriptions)?

This page provides optimized solutions for LeetCode problem 2196 (Create Binary Tree From Descriptions) in Java, C++, and Python, along with a detailed explanation and an interactive code editor to test your code.

What is the time complexity of LeetCode 2196 (Create Binary Tree From Descriptions)?

The time complexity for LeetCode 2196 (Create Binary Tree From Descriptions) varies by solution. Check the detailed explanation section for specific complexities in Java, C++, and Python implementations.

Can I run code for LeetCode 2196 on DevExCode?

Yes, DevExCode provides an interactive code editor where you can write, test, and run your code for LeetCode 2196 in Java, C++, or Python.

Back to LeetCode Solutions