Leetcode-construct Binary Tree from preorder and inorder traversal

Source: Internet
Author: User

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

Note:

Assume that duplicates does not exist in the tree.


Class Solution {Private:treenode *root;    Vector<int> Mypreorder; Vector<int> myinorder;public:treenode *createtree (TreeNode *root,int pre,int in,int lenth) {int l,r,r        Ootpos;        if (lenth<=0) root=null;                        else {//new node Root=new TreeNode (Mypreorder[pre]); Find root for (int i=in;i<=in+lenth-1;i++) if (Root->val==myinorder[i]) rootpo                        S=i;            Sub-tree length l=rootpos-in;                        R=LENTH-L-1;            Build subtree Root->left=createtree (root->left,pre+1,in,l);        Root->right=createtree (Root->right, pre+1+l,rootpos+1,r);    } return root; } TreeNode *buildtree (vector<int> &preorder, vector<int> &inorder) {if (Preorder.size () &                lt;=0) return NULL;        Copy Mypreorder=preorder;          Myinorder=inorder;      Build Root=createtree (Root,0,0,preorder.size ());    return root; }};


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.