Leetcode first brush _ Construct Binary Tree from Inorder and Postorder Traversal

Source: Internet
Author: User

This question is one of the few questions I have encountered while studying undergraduate courses. What is the manual construction process? The next traversal of the last node must be the root node of the entire tree. This element is found in the Middle-order traversal, the tree can be divided into two Subtrees. The left subtree is recursively constructed on the left of this element, and the right subtree is recursively constructed on the right. The element itself allocates space as the root node.

The difference between the set and map containers is that the vector container does not include the find member function, and the stl library function should be used. Fortunately, the returned iterator is also used, the iterators of the vector can be used for subtraction, And the offset can be easily obtained.

TreeNode * buildRec (vector <int> & inorder, int si, vector <int> & postorder, int so, int len) {if (len <= 0) return NULL; treeNode * root = new TreeNode (postorder [so]); int index = find (inorder. begin (), inorder. end (), postorder [so])-inorder. begin (); int newlen = index-si; root-> left = buildRec (inorder, si, postorder, so-len + newlen, newlen ); root-> right = buildRec (inorder, index + 1, postorder, so-1, len-newlen-1); return root;} class Solution {public: treeNode * buildTree (vector <int> & inorder, vector <int> & postorder) {return buildRec (inorder, 0, postorder, inorder. size ()-1, inorder. size ());}};


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.