日期:2026年6月7日
LeetCode 題目連結:2196. Create Binary Tree From Descriptions
解題想法
中級難度的題目。要用鏈結串列建二元樹。我先將每個節點的父節點、左子樹、右子樹分別存入字典之中,另外用一個集合儲存所有的節點。再找根節點,也就是所有節點當中唯一一個沒有父節點的節點。最後再用 BFS 或遞迴建樹。以下的程式碼速度不快,還可以再改進。
Python 程式碼
用 list 儲存待走訪的節點。Runtime: 202 ms, beats 15.04%. Memory: 28.30 MB, beats 24.19%.
# 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]:
# 儲存所有的節點值,記錄每個節點的父節點、左子節點、右子節點
parent = dict()
left_child = dict()
right_child = dict()
all_nodes = set()
for p, c, lr in descriptions:
all_nodes.add(p)
all_nodes.add(c)
parent[c] = p
if lr == 1:
left_child[p] = c
else:
right_child[p] = c
# 找出根節點的值
root_val = -1
for node in all_nodes:
if node not in parent:
root_val = node
break
# 用 list 建樹
root = TreeNode(val=root_val)
que = [root]
head = 0
while head < len(que):
curr = que[head]
head += 1
if curr.val in left_child:
curr.left = TreeNode(val = left_child[curr.val])
que.append(curr.left)
if curr.val in right_child:
curr.right = TreeNode(val = right_child[curr.val])
que.append(curr.right)
return root