《劍指offer》面試題7:重建二叉樹

題目描述

知識點:二叉樹,遞歸

思路:
pre爲先序遍歷序列,tin爲中序遍歷序列

  • pre的第一個元素爲根節點的值,tin以root爲分界點
  • root的索引爲i
  • tin前半部分[:i]爲左子樹,後半部分[i+1:]爲右子樹
  • pre[1:i+1]爲左子樹,[i+1:]爲右子樹
  • 遞歸構造
class TreeNode:
    def __init__(self, x):
        self.val = x
        self.left = None
        self.right = None
        
class Solution:
    # 返回構造的TreeNode根節點
    def reConstructBinaryTree(self, pre, tin):
        # write code here
        if not pre and not tin:
            return None
        if set(pre) != set(tin):
            return None
        
        root = TreeNode(pre[0])
        
        i = tin.index(pre[0])
        
        root.left = self.reConstructBinaryTree(pre[1:i+1], tin[:i])    # 左子樹
        root.right = self.reConstructBinaryTree(pre[i+1:], tin[i+1:])    # 右子樹
        
        return root
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章