Leetcode:construct Binary Tree from preorder and inorder traversal

Source: Internet
Author: User

Title Description:

Given Preorder and inorder traversal of a tree, construct the binary tree.

Note:
Assume that duplicates does not exist in the tree.


Problem solving: The first element of the first order traversal is the root element, and the position of the root element is found in the middle sequence traversal sequence. The middle sequence traverses the root element to the left of the record sequence, and to the right is the sequential traversal sequence of the right sub-tree. According to the length of sequence traversal sequences in the left and right sub-tree, the first sequence traversal sequence can be divided into two parts, the first sequence traversal sequence of Zuozi on the left, and the first sequence traversal sequence of the starboard tree on the right. The first order sequence and sequence of the left and right subtree are known, and the result can be obtained by invoking the above method recursively on the left and the sub-tree.


Code:

TreeNode * Build_tree (Vector<int>::iterator prel,vector<int>::iterator prer,vector<int>:: Iterator inl,vector<int>::iterator INR) {    if (prel >= prer)        return NULL;    TreeNode * ROOT;    if (Prer-prel = = 1)    {        root = new TreeNode (0);        Root->val = *prel;        return root;    }    root = new TreeNode (0);    Root->val = *prel;    Vector<int>::iterator Root_pos = Find (inl,inr,root->val);    int left_length = ROOT_POS-INL;    Root->left = Build_tree (prel+1,prel+1+left_length,inl,inl+left_length);    Root->right = Build_tree (PREL+1+LEFT_LENGTH,PRER,INL+LEFT_LENGTH+1,INR);    return root;} TreeNode * Solution::buildtree (vector<int> &preorder, vector<int> &inorder) {    return build_ Tree (Preorder.begin (), Preorder.end (), Inorder.begin (), Inorder.end ());


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.