[4] wins the Offer. Binary tree reconstruction (Python implementation)

Title Description

And enter the result in a preorder traversal of a binary tree in preorder traversal of the binary tree a rebuild. Suppose Results preorder traversal order and input of duplicate numbers are free. Before entering e.g. preorder traversal sequence {1,2,4,7,3,5,6,8} and {4,7,2,1,5,3,8,6} order traversal sequence, and the reconstructed binary tree return.

Solution one: recursion

# -*- coding:utf-8 -*-
# class TreeNode:
#     def __init__(self, x):
#         self.val = x
#         self.left = None
#         self.right = None
class Solution:
    def reConstructBinaryTree(self, pre, tin):
    	# 边界条件
        if not pre or not tin:
            return None
        # 前序根节点和中序索引
        root = TreeNode(pre.pop(0))
        index = tin.index(root.val)
        root.left = self.reConstructBinaryTree(pre, tin[:index])
        root.right = self.reConstructBinaryTree(pre, tin[index + 1:])
        return root

 

Published 60 original articles · won praise 18 · views 10000 +

Guess you like

Origin blog.csdn.net/qq_36936730/article/details/104572432