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:
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
- Because the node in the first order is the root node, the first node of the first order is taken out
- 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.
- 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