Construct Binary Tree from preorder and inorder traversal

Source: Internet
Author: User

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

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.