Leetcode–refresh–construct Binary Tree from inorder and Postorder traversal

Source: Internet
Author: User

For this problem just need to know the structure of both traversal.

1. It's hard-to-find the root node in the Inorder traversal but it's easy in postorder. The last one on post order is the root.

2. At same time, you can not be a figure out of what's the boundary for left branch and right branch in post order. But the can do it in inorder.

1 /**2 * Definition for binary tree3 * struct TreeNode {4 * int val;5 * TreeNode *left;6 * TreeNode *right;7 * TreeNode (int x): Val (x), left (null), right (null) {}8  * };9  */Ten classSolution { One  Public: ATreeNode *gettree (vector<int> &iv, vector<int> &AMP;PV,intIstintIedintPstintPED) { -         if(Ist > IED)returnNULL; -         intCurrent =-1, Len =0; the          for(inti = ist; I <= IED; i++) { -             if(pv[ped] = =Iv[i]) { -Current =i; -                  Break; +             } -         } +Len = current-ist; ATreeNode *root =NewTreeNode (pv[ped]); atRoot->left = Gettree (iv, PV, ist, current-1, PST, pst+len-1); -Root->right = Gettree (iv, PV, current+1, IED, Pst+len, ped-1); -     } -TreeNode *buildtree (vector<int> &inorder, vector<int> &postorder) { -         if(inorder.size () = =0|| Inorder.size ()! = Postorder.size ())returnNULL; -         returnGettree (Inorder, Postorder,0, Inorder.size ()-1,0, Postorder.size ()-1); in     } -};

Leetcode–refresh–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.