#2196
Create Binary Tree From Descriptions
MediumArrayHash TableTreeBinary TreeHash MapArray
Approaches
Brute ForceOptimal
Complexity Comparison
| Brute Force | Optimal Solution★ | |
|---|---|---|
| Time | O(n²) | O(n) |
| Space | O(1) | O(n) |
💡
Intuition
Time O(n)Space O(n)
The optimal approach utilizes a hashmap to store nodes and a set to track children, allowing us to efficiently build the tree in a single pass and quickly identify the root node.
⚙️
Algorithm
3 steps- 1Step 1: Initialize a hashmap to store TreeNode objects and a set to track all child nodes.
- 2Step 2: For each description, create the parent and child nodes if they don't exist, and link them based on isLeft.
- 3Step 3: After processing all descriptions, find the root node (the one not present in the child set).
solution.py22 lines
1class TreeNode:
2 def __init__(self, val=0, left=None, right=None):
3 self.val = val
4 self.left = left
5 self.right = right
6
7def createBinaryTree(descriptions):
8 nodes = {}
9 children = set()
10 for parent, child, isLeft in descriptions:
11 if parent not in nodes:
12 nodes[parent] = TreeNode(parent)
13 if child not in nodes:
14 nodes[child] = TreeNode(child)
15 if isLeft:
16 nodes[parent].left = nodes[child]
17 else:
18 nodes[parent].right = nodes[child]
19 children.add(child)
20 for node in nodes:
21 if node not in children:
22 return nodes[node]ℹ
Complexity note: The time complexity is O(n) because we process each description exactly once, and the space complexity is O(n) due to storing the nodes in a hashmap.
- 1The root node is the only node that does not appear as a child.
- 2Using a hashmap allows for quick access and insertion of nodes.
Solutions and explanations are original Tejav content. Problem titles © LeetCode — use the LeetCode button above for the full problem statement.