[Leetcode] Construct binary tree from inorder and postorder traversal

Source: Internet
Author: User

Given Inorder and Postorder traversal of a tree, construct the binary tree.

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


Postorder for the left and right, so postorder the last one for the root, after obtaining the root, in inorder can find the elements of the Zuozi and the subtree.

The problem can be decomposed into, finding roots, determining the elements of Zuozi and right subtrees. So, recursive solution.

Because Postorder stores the root node from left to right, the right subtree is constructed first.


/** * definition for binary tree * struct treenode { *      int val; *     TreeNode *left; *      treenode *right; *     treenode (int x)  :  val (x),  left (null),  right (null)  {} * }; */class solution {public :     int postindex;    treenode *buildtree (vector<int>  &inorder, vector<int> &postorder)  {         if (inorder.size () ==0| | Postorder.size () ==0)             return NULL;               postindex=postorder.size () -1;        int stat=0;    &nbsP;   int end=postorder.size () -1;        return  foo (inorder,postorder,stat,end);                             }     treenode* foo (Vector<int> &inorder,vector<int> &postorder,int  stat,int end) {        if (stat>end)              return NULL;         treenode* root=new treenode (0);        root-> val=postorder[postindex];        postindex=postindex-1;         int indexofroot=index (Inorder,root->val);         if (iNdexofroot==-1)             exit (0);         if (stat==end)              return root;        root->right=foo (Inorder, Postorder,indexofroot+1,end);         root->left=foo (Inorder, POSTORDER,STAT,INDEXOFROOT-1);                 return root;            }         int index (Vector<int> v,int val) {         int i;        for (i=0;i <v.size (); i++)             if (v[i]==val)                  return i;         return -1;    }    };


[Leetcode] Construct binary tree from inorder and postorder 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.