# 重建二叉樹

``````class TreeNode:
def __init__(self, x):
self.val = x
self.left = None
self.right = None

class Solution:
def reConstructBinaryTree(self, pre, tin):
if not pre or not tin: #判斷是否爲None
return None
root = TreeNode(pre.pop(0))
#root爲前序的頭節點
index = tin.index(root.val)
#index爲root的當前值在tin中的位置
root.left = self.reConstructBinaryTree(pre, tin[:index])
#tin[:index]意思是從0開始輸出index個個數中序的值,左邊的全是跟的左子樹
root.right = self.reConstructBinaryTree(pre, tin[index+1:])
#tin[index + 1:]意思是從第index+2後所有元素,全是跟的右子樹部分
return root
``````

1、爲什麼倒數第二行是tin[index+1:]

2、爲什麼pre沒有變化，上下的都是pre

3、爲什麼是 if not pre or not tin 而不是 if pre == None or tin == None

(1) if x is None:
(2) if not x:
(3) if not x is None:（這句這樣理解更清晰`if not (x is None)`

``````>>> x = 1
>>> not x
False
>>> x = [1]
>>> not x
False
>>> x = 0
>>> not x
True
>>> x = [0]     # You don't want to fall in this one.
>>> not x
False
``````

``````>>> x = []
>>> y = None
>>>
>>> x is None
False
>>> y is None
True
>>>
>>>
>>> not x
True
>>> not y
True
>>>
>>>
>>> not x is None
True
>>> not y is None
False
``````

`if x is not None`是最好的寫法，清晰，不會出現錯誤，以後堅持使用這種寫法。

### 另一個python解法

``````class Solution:
# 返回構造的TreeNode根節點
def reConstructBinaryTree(self, pre, tin):
# write code here
if len(pre) == 0:
return None
elif len(pre) == 1:
return TreeNode(pre[0])
else:
ans = TreeNode(pre[0])
ans.left = self.reConstructBinaryTree(pre[1:tin.index(pre[0])+1],   tin[:tin.index(pre[0])])
ans.right = self.reConstructBinaryTree(pre[tin.index(pre[0])+1:], tin[tin.index(pre[0])+1:])
return ans``````