Written Test Algorithm---Binary Tree Reconstruction

# -*- coding:utf-8 -*-
# class TreeNode:
#     def __init__(self, x):
#         self.val = x
#         self.left = None
#         self.right = None
class Solution:
    # Return the constructed TreeNode root node
    def reConstructBinaryTree(self, pre, tin):
        # write code here
        if len (pre) == 0:
            return None
        if len (pre) == 1:
            return TreeNode(pre[0])
        else:
            flag = TreeNode(pre[0])
            flag.left = self.reConstructBinaryTree(pre[1:tin.index(pre[0])+1],tin[:tin.index(pre[0])])
            flag.right = self.reConstructBinaryTree(pre[tin.index(pre[0])+1:],tin[tin.index(pre[0])+1:] )
        return flag
Considering the situation, there are no nodes, except for a single node, and the rest are added according to the characteristics of pre-order traversal and in-order traversal.

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=325709719&siteId=291194637