我遇到了這個問題,我的任務是將元組轉換為二叉樹,然后將二叉樹轉換回元組并回傳樹和元組。我能夠將元組轉換為樹,但我未能創建一個函式來執行相反的操作。我只是一個嘗試學習資料結構的初學者。
這里的 parse_tuple 函式用于決議元組以創建一個作業正常的二叉樹。
請幫我修復我的 tree_to_tuple 函式。任何解決邏輯的見解或技巧都會很棒。
謝謝
#used for creating binary tree
class TreeNode:
def __init__(self, key):
self.key = key
self.left = None
self.right = None
#used to parse over the tuple to create a bianry tree
def parse_tuple(data):
if isinstance(data, tuple) and len(data) == 3:
node = TreeNode(data[1])
node.left = parse_tuple(data[0])
node.right = parse_tuple(data[2])
elif data is None:
node = None
else:
node = TreeNode(data)
return node
#doesnt work
def tree_to_tuple(node):
if isinstance(node, TreeNode) and node.left is not None and node.right is not None:
node_mid = node.key
node_left = tree_to_tuple(node.left)
node_right = tree_to_tuple(node.right)
elif node.left is None:
node_left = None
else:
node_right = None
return (node_left, node_mid, node_right)
tree_tuple = ((1, 3, None), 2, ((None, 3, 4), 5, (6, 7, 8)))
tree2 = parse_tuple(tree_tuple)
tree_tuple2 = (1, 2, 3)
tree = parse_tuple(tree_tuple2)
print(tree_to_tuple(tree2))
這是我嘗試使用 tree_to_tuple 時遇到的錯誤
檔案“main.py”,第 45 行,在 tree_to_tuple 中 return (node_left, node_mid, node_right) UnboundLocalError: 在賦值之前參考了區域變數 'node_left'。
uj5u.com熱心網友回復:
你很接近,但你的測驗有點混亂。
這是一個補丁:
def tree_to_tuple(node):
if isinstance(node, TreeNode):
# special case if the tree has no left and no right sub-tree
if node.left is None and node.right is None:
return node.key
return (
tree_to_tuple(node.left),
node.key,
tree_to_tuple(node.right)
)
raise ValueError('this is not a tree')
tree_tuple = ((1, 3, None), 2, ((None, 3, 4), 5, (6, 7, 8)))
tree2 = parse_tuple(tree_tuple)
tree_tuple2 = (1, 2, 3)
tree = parse_tuple(tree_tuple2)
print(tree_to_tuple(tree2))
輸出:
((1, 3, None), 2, ((None, 3, 4), 5, (6, 7, 8)))
轉載請註明出處,本文鏈接:https://www.uj5u.com/caozuo/328822.html
上一篇:基于遞回的python排列演算法
