Leetcode Construct Binary Tree from preorder and inorder traversal

Source: Internet
Author: User

Leetcode problem Solving construct Binary Tree from preorder and inorder traversal original problem

The tree structure of a binary tree is obtained by its pre-order and middle order arrangement.

Note the point:

    • No

Example:

Input: Preorder = [3,9,20,15,14,7], inorder = [9,3,14,15,20,7]

Output:

    3     9  20    /     15   7  / 14
Thinking of solving problems
    1. Because the node in the first order is the root node, the first node of the first order is taken out
    2. The first node of the first order can divide the middle order into the left and right sub-trees, then take out the second section of the first order and divide the left-right sub-tree again.
    3. Ends when the middle order is all divided into a single point

At the beginning of recursion, a list is used as a parameter, and the result is memory overflow, using subscript as parameter, first order and sequence as global variables.

AC Source
# Definition for a binary tree node. class TreeNode(object):     def __init__(self, x):Self.val = x Self.left =NoneSelf.right =None class solution(object):     def buildtree(self, preorder, inorder):        "" : Type Preorder:list[int]: type Inorder:list[int]: Rtype:treenode "" "Self.preorder = Preorder Self.inorder = inorderreturnSelf._buildtree (0, Len (preorder),0, Len (inorder)) def _buildtree(self, Pre_start, pre_end, In_start, In_end):        ifPre_start >= Pre_end:return NoneRoot = TreeNode (Self.preorder[pre_start]) offset = self.inorder[in_start:in_end +1].index (root.val) root.left = Self._buildtree (Pre_start +1, Pre_start + offset +1, In_start, In_start + offset) root.right = self._buildtree (Pre_start + offset +1, pre_end, In_start + offset +1, In_end)returnRootif__name__ = ="__main__":None

Welcome to my GitHub (Https://github.com/gavinfish/LeetCode-Python) to get the relevant source code.

Leetcode Construct Binary Tree from preorder and inorder traversal

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.