1. 程式人生 > >根據前序和中序構建二叉樹

根據前序和中序構建二叉樹

進行遞迴

# -*- 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 not pre and not tin:
            return None
        root = TreeNode(pre[0])
        index = tin.index(pre[0])
        root.left = self.reConstructBinaryTree(pre[1:index+1],tin[0:index])
        root.right = self.reConstructBinaryTree(pre[index+1:],tin[index+1:])
        return root