1. 程式人生 > >[Leetcode][python]從前序與中序遍歷序列構造二叉樹/從中序與後序遍歷序列構造二叉樹

[Leetcode][python]從前序與中序遍歷序列構造二叉樹/從中序與後序遍歷序列構造二叉樹

題目大意

根據二叉樹的前序遍歷和中序遍歷( 中序和後序)結果生成二叉樹
假設沒有重複數字

解題思路

參考給中序和後序遍歷
看到樹首先想到要用遞迴來解題。以這道題為例:如果一顆二叉樹為{1,2,3,4,5,6,7},則中序遍歷為{4,2,5,1,6,3,7},後序遍歷為{4,5,2,6,7,3,1},我們可以反推回去。由於後序遍歷的最後一個節點就是樹的根。也就是root=1,然後我們在中序遍歷中搜索1,可以看到中序遍歷的第四個數是1,也就是root。根據中序遍歷的定義,1左邊的數{4,2,5}就是左子樹的中序遍歷,1右邊的數{6,3,7}就是右子樹的中序遍歷。而對於後序遍歷來講,一定是先後序遍歷完左子樹,再後序遍歷完右子樹,最後遍歷根。於是可以推出:{4,5,2}就是左子樹的後序遍歷,{6,3,7}就是右子樹的後序遍歷。而我們已經知道{4,2,5}就是左子樹的中序遍歷,{6,3,7}就是右子樹的中序遍歷。再進行遞迴就可以解決問題了。

前序和中序:

root.left = self.buildTree(preorder[1 : index + 1], inorder[0 : index])
root.right = self.buildTree(preorder[index + 1 : len(preorder)], inorder[index + 1 : len(inorder)])

中序和後序:

root.left = self.buildTree(inorder[0 : index], postorder[0 : index])
root.right = self.buildTree(inorder[index
+ 1 : len(preorder)], postorder[index : len(inorder)-1])

程式碼

前序和中序

class Solution(object):
    def buildTree(self, preorder, inorder):
        if len(preorder) == 0:
            return None
        if len(preorder) == 1:
            return TreeNode(preorder[0])
        root = TreeNode(preorder[0
]) index = inorder.index(root.val) # 中序中根節點的位置,左邊即為左子樹,右邊由子樹 root.left = self.buildTree(preorder[1 : index + 1], inorder[0 : index]) root.right = self.buildTree(preorder[index + 1 : len(preorder)], inorder[index + 1 : len(inorder)]) return root

中序和後序

class Solution(object):
    def buildTree(self, inorder, postorder):
        if len(inorder) == 0:
            return None
        if len(inorder) == 1:
            return TreeNode(inorder[0])
        root = TreeNode(postorder[len(postorder) - 1])
        index = inorder.index(postorder[len(postorder) - 1])
        root.left = self.buildTree(inorder[ 0 : index ], postorder[ 0 : index ])
        root.right = self.buildTree(inorder[ index + 1 : len(inorder) ], postorder[ index : len(postorder) - 1 ])
        return root

總結

二叉樹遍歷

  1. 二叉樹的前序、中序、後序遍歷(深度優先遍歷)
    遍歷即將樹的所有結點都訪問且僅訪問一次。按照根結點訪問次序的不同,可以分為前序遍歷,中序遍歷,後序遍歷。
    前序遍歷:根結點 -> 左子樹 -> 右子樹
    中序遍歷:左子樹 -> 根結點 -> 右子樹
    後序遍歷:左子樹 -> 右子樹 -> 根結點
    這裡寫圖片描述
    前序遍歷:abdefgc
    中序遍歷:debgfac
    後序遍歷:edgfbca

  2. 層次遍歷(廣度優先遍歷)
    層次遍歷:abcdfeg