重建二叉樹

題目描述

輸入某二叉樹的前序遍歷和中序遍歷的結果,請重建出該二叉樹。假設輸入的前序遍歷和中序遍歷的結果中都不含重複的數字。例如輸入前序遍歷序列{1,2,4,7,3,5,6,8}和中序遍歷序列{4,7,2,1,5,3,8,6},則重建二叉樹並返回。

以中序和前後序建成樹的思想已經不用再闡述了,遍歷樹主要靠的是遞歸

代碼展示

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:]

答:因爲是右子樹部分,若是tin[index:]則包含了root本身

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

答:因爲pop掉了前序的第一個,也就是樹整體的根,且是處理完了左子樹,纔會處理右子樹,按照前序序列左子樹一個個pop掉,當先處理左子樹的時候pre[:index-1]就是pre,所以,上面的pre非下面的pre。

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

答:網上有這樣的答案

代碼中經常有三種方式判斷變量是否爲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

在python中 None, False, 空字符串"", 0, 空列表[], 空字典{}, 空元組()都相當於False ,因此在使用列表的時候,如果你想區分x==[]和x==None兩種情況的話, 此時if not x:將會出現問題:

>>> 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

也許你是想判斷x是否爲None,但是卻把x==[]的情況也判斷進來了,此種情況下將無法區分。
對於習慣於使用if not x這種寫法的pythoner,必須清楚x等於None, False, 空字符串"", 0, 空列表[], 空字典{}, 空元組()時對你的判斷沒有影響才行。
而對於if x is not Noneif not x is None寫法,很明顯前者更清晰,而後者有可能使讀者誤解爲if (not x) is None,因此推薦前者,同時這也是谷歌推薦的風格

結論:
if x is not None是最好的寫法,清晰,不會出現錯誤,以後堅持使用這種寫法。
使用if not x這種寫法的前提是:必須清楚x等於None, False, 空字符串"", 0, 空列表[], 空字典{}, 空元組()時對你的判斷沒有影響才行。

另一個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


轉載鏈接:https://www.jianshu.com/p/86dea051d145
 

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章