題目:
我依舊不想打檩咱,如題
主要學(xué)習(xí)一下遞歸思想扎附,別的沒了
然后就是生成一個樹節(jié)點膨处,取列表指定樹的下標(biāo)
代碼
def reConstructBinaryTree(pre,tin):
if not pre or not tin:
return None
root = TreeNode(pre[0])
tin_index = tin.index(pre[0])
left = self.reConstructBinaryTree(pre[1:], tin[:tin_index])
right = self.reConstructBinaryTree(pre[tin_index+1:], tin[tin_index + 1:])
if left:
root.left = left
if right:
root.right = right
return root
為了測試用例健爬,寫了一個二叉樹的打印
class TreeNode:
def __init__(self, x):
self.val = x
self.left = None
self.right = None
def print_tree(self):
if self.left:
self.left.print_tree()
print self.val
if self.right:
self.right.print_tree()