The topic requires that the binary tree be reconstructed by the result of the traversal of the former sequence and the middle order binary tree. There is no redundancy in the node value of the tree.
The solution is to give the index of the beginning and end of the current process of the pre-order and the middle sequence. The first value of the preamble is the value of the root node, which, based on this value, looks for index in the middle order, thus dividing the traversal of the Saozi right subtree in the middle order, recursively solving, until only one node. Note that in order to perform an efficient lookup of the sequential traversal, the values are pre-deposited into the hashmap, and the Python implementation is dict.
Class solution (Object): def buildtree (self, Preorder, inorder): "" " : Type Preorder:list[int] : Type Inorder:list[int] : Rtype:treenode "" " If not preorder: return None map ={} length = Len ( Preorder) for I in xrange (length): map[inorder[i]] = i return self.helper (preorder,0,length-1,0, Length-1,map) def Helper (self,preorder,pstart,pend,istart,iend,map): if Pstart > Pend: return None node = TreeNode (Preorder[pstart]) if Pstart = = Pend: return node i = Map[preorder[pstart]] node.left = Self.helper (preorder,pstart+1,i-istart+pstart,istart,i-1,map) node.right = Self.helper ( PREORDER,I-ISTART+PSTART+1,PEND,I+1,IEND,MAP) return node
The time complexity is O (n), each node needs to be traversed once, and the recursive function stack is O (logn). Because the DICT is established, the final spatial complexity is O (n),
Construct Binary Tree from preorder and inorder traversal