Skip to content

Latest commit

 

History

History
51 lines (37 loc) · 1.36 KB

_2196. Create Binary Tree From Descriptions.md

File metadata and controls

51 lines (37 loc) · 1.36 KB

All prompts are owned by LeetCode. To view the prompt, click the title link above.

Back to top


First completed : July 15, 2024

Last updated : July 15, 2024


Related Topics : Array, Hash Table, Tree, Binary Tree

Acceptance Rate : 81.76 %


Solutions

Python

# Definition for a binary tree node.
# 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]:
        children = set()
        nodes = {}

        for p, c, isleft in descriptions :
            nodes[p] = nodes.get(p, TreeNode(val=p))
            nodes[c] = nodes.get(c, TreeNode(val=c))

            if isleft :
                nodes[p].left = nodes[c]
            else :
                nodes[p].right = nodes[c]

            children.add(nodes[c])

        return list(set(nodes.values()) - children)[0]