This commit is contained in:
parent
a8d01d000d
commit
7f690e912e
1 changed files with 26 additions and 0 deletions
26
medium/create_binary_tree_from_descriptions.py
Normal file
26
medium/create_binary_tree_from_descriptions.py
Normal file
|
|
@ -0,0 +1,26 @@
|
||||||
|
# https://leetcode.com/problems/create-binary-tree-from-descriptions
|
||||||
|
from typing import Dict, List, Optional
|
||||||
|
|
||||||
|
class TreeNode:
|
||||||
|
def __init__(self, val=0, left=None, right=None):
|
||||||
|
self.val = val
|
||||||
|
self.left = left
|
||||||
|
self.right = right
|
||||||
|
class Solution:
|
||||||
|
def createBinaryTree(self, descriptions: List[List[int]]) -> Optional[TreeNode]:
|
||||||
|
nodes: Dict[int, TreeNode] = {}
|
||||||
|
s = set()
|
||||||
|
for head, next, left in descriptions:
|
||||||
|
if nodes.get(head) is None:
|
||||||
|
nodes[head] = TreeNode(head)
|
||||||
|
if nodes.get(next) is None:
|
||||||
|
nodes[next] = TreeNode(next)
|
||||||
|
if left:
|
||||||
|
nodes[head].left = nodes[next]
|
||||||
|
else:
|
||||||
|
nodes[head].right = nodes[next]
|
||||||
|
s.add(next)
|
||||||
|
for node in nodes:
|
||||||
|
if node not in s:
|
||||||
|
return nodes[node]
|
||||||
|
|
||||||
Loading…
Add table
Add a link
Reference in a new issue