劍指Offer(四):重建二叉樹

1、前言

刷題平臺:牛客網php

2、題目

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

一、思路

一般樹有以下幾種遍歷方式:url

  • 前序遍歷:先訪問根結點,再訪問左子結點,最後訪問右子結點。
  • 中序遍歷:先訪問左子結點,再訪問根結點,最後訪問右子結點。
  • 後序遍歷:先訪問左子結點,再訪問右子結點,最後訪問根結點。

本題爲前序遍歷和中序遍歷,最少須要兩種遍歷方式,才能重建二叉樹。spa

前序遍歷序列中,第一個數字老是樹的根結點的值。在中序遍歷序列中,根結點的值在序列的中間,左子樹的結點的值位於根結點的值的左邊,而右子樹的結點的值位於根結點的值的右邊。剩下的咱們能夠遞歸來實現,具體如圖:code

劍指Offer(四):重建二叉樹

二、代碼

Python:blog

# -*- coding:utf-8 -*-
# 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 len(pre) == 0:
            return None
        elif len(pre) == 1:
            return TreeNode(pre[0])
        else:
            root = TreeNode(pre[0])
            pos = tin.index(pre[0])
            root.left = self.reConstructBinaryTree(pre[1:pos+1], tin[:pos])
            root.right = self.reConstructBinaryTree(pre[pos+1:], tin[pos+1:])
        return root
相關文章
相關標籤/搜索