面试题7: 重建二叉树

二叉树

前序遍历:根左右

中序遍历:左跟右

后序遍历:左右根

 

# -*- 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 or not tin:
            return None
        # 先确定根结点为前序遍历的第一个元素
        root = TreeNode(pre[0])
        #在中序遍历中寻找根节点的索引
        val = tin.index(pre[0])
        #采用递归实现重建
        #左子树就是中序遍历的根节点左侧
        root.left = self.reConstructBinaryTree(pre[1:val+1],tin[:val])
        #同理,右子树
        root.right = self.reConstructBinaryTree(pre[val+1:],tin[val+1:])
        return root

  

posted @ 2019-07-19 21:55  lililili——  阅读(178)  评论(0)    收藏  举报