"Leetcode" Construct Binary Tree from preorder and inorder traversal

Source: Internet
Author: User

Construct Binary Tree from preorder and inorder traversal

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

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

It can be compared with construct Binary Tree from Inorder and postorder traversal.

The first node of the preorder traversal is the root, and because there are no duplicate values, you can use the root to divide the middle order inorder into left and right subtrees.

recursively.

/** Definition for binary tree * struct TreeNode {* int val; * TreeNode *left; * TreeNode *right; * T Reenode (int x): Val (x), left (null), right (NULL) {} *}; */classSolution { Public: TreeNode*buildtree (vector<int> &preorder, vector<int> &inorder) {        returnHelper (Preorder,0, Preorder.size ()-1, Inorder,0, Inorder.size ()-1); } TreeNode*helper (vector<int> &preorder,intBegin1,intEnd1, vector<int> &inorder,intBegin2,intEnd2) {        if(Begin1 >end1)returnNULL; Else if(Begin1 = =end1)return NewTreeNode (preorder[begin1]); Else        {            //Preorder[begin1] is the roottreenode* root =NewTreeNode (preorder[begin1]); intIND;  for(Ind = begin2; ind <= END2; IND + +))            {                if(Inorder[ind] = =Preorder[begin1]) Break; }            // LeftRoot->left = Helper (Preorder, begin1+1, Ind-begin2+begin1, Inorder, Begin2, ind-1); // RightRoot->right = Helper (Preorder, end1-end2+ind+1, End1, Inorder, ind+1, End2); returnRoot; }    }};

"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.