《劍指offer》第4題:重建二叉樹

1 題目描述

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

2 分析及題解

  根據前序和中序遍歷順序:
  前序遍歷:根節點→左子樹→右子樹
  中序遍歷:左子樹→根節點→右子樹
  之後找到根節點,劃分左子樹和右子樹,遞歸

class Solution1:
    def reConstructBinaryTree(self, pre, tin):
        # write code here
        if len(pre) < 1 or len(tin) < 1:
            return None
        if len(pre) == 1 or len(tin) == 1:
            return TreeNode(pre[0])

        root = TreeNode(pre[0])
        tinL = tin[:tin.index(pre[0])]
        tinR = tin[tin.index(pre[0]) + 1:]
        root.left = self.reConstructBinaryTree(pre[1:tin.index(pre[0]) + 1], tinL)
        root.right = self.reConstructBinaryTree(pre[tin.index(pre[0]) + 1:], tinR)

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