面试题七:重建二叉树

题目:输入某二叉树的前序遍历和中序遍历的结果,请重建该二叉树。

代码:前序遍历的第一个数字为根节点的值,中序遍历同样的数字表示根节点的位置,之前的数字为左子树节点的值,之后的数字为右子树的值,同样的数字为前序遍历左右子树的结果,递归该过程。

# -*- 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

猜你喜欢

转载自blog.csdn.net/houyaqiong/article/details/81318885