面试题07:重建二叉树(Python)

题目链接:https://www.nowcoder.com/practice/8a19cbe657394eeaac2f6ea9b0f6fcf6?tpId=13&tqId=11157&tPage=1&rp=1&ru=/ta/coding-interviews&qru=/ta/coding-interviews/question-ranking

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

 

你可能感兴趣的:(面试题07:重建二叉树(Python))