1. 程式人生 > >[算法題] 重建二叉樹

[算法題] 重建二叉樹

tree 描述 rec 利用 node clas python代碼 class ini

題目描述

輸入某二叉樹的前序遍歷和中序遍歷的結果,請重建出該二叉樹。假設輸入的前序遍歷和中序遍歷的結果中都不含重復的數字。

題目思路

本題就是按照建立二叉樹的思路建立就行了。先序遍歷的第一個是根節點,然後在中序遍歷找到該根節點,以此為界,中序遍歷的左邊是它的左子樹的中序遍歷,同樣地找到該左子樹在先序遍歷中對應的先序遍歷順序。對於右子樹也是一樣的方法。

本體采用遞歸,遞歸就要先寫出終止條件。

Python代碼

這個題目用Python非常方便,因為可以直接利用到Python中的切片技術,省時省力通俗易懂。Java版本相對復雜得多。

# -*- 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 or len(tin)==0: return
if len(pre)==1: return TreeNode(pre[0]) node=TreeNode(pre[0]) for i in range(len(tin)): if tin[i]==pre[0]: break node.left=self.reConstructBinaryTree(pre[1:i+1],tin[:i]) node.right=self.reConstructBinaryTree(pre[i+1:],tin[i+1:])
return node

[算法題] 重建二叉樹