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

Subscribe to see which companies asked this question

Idea: The last element of the subsequent traversal is the root node, through this root node, you can divide the sequence of elements to the left and right sub-tree of the other parts, to determine the establishment of the right and right subtree of the sequence traversal and subsequent traversal element subscript range, through this range recursive call function Help, continue to establish the left and right subtree, Finally, the left and right subtrees are connected to root and returned to root.

  
 
  1. /**
  2. * Definition for a binary tree node.
  3. * struct TreeNode {
  4. * int val;
  5. * TreeNode *left;
  6. * TreeNode *right;
  7. * TreeNode(int x) : val(x), left(NULL), right(NULL) {}
  8. * };
  9. */
  10. class Solution {
  11. public:
  12. Span class= "Typ" >treenode * Buildtree ( vector <INT> & inorder vector span class= "str" ><INT> & Postorder {
  13. if(inorder.size()==0)//节点数目为0,直接返回NULL
  14. return NULL;
  15. return help(inorder,0,inorder.size()-1,postorder,0,postorder.size()-1);
  16. }
  17. Span class= "Typ" >treenode * help ( vector <INT> & inorder int Start1 int End1 vector <INT> Postorder int Start2 int End2
  18. if(start1>end1)//下标越界,返回NULL
  19. return NULL;
  20. int val = postorder[end2];//取出根节点的值
  21. TreeNode * root =new TreeNode (val);//建立根节点
  22. int i;
  23. for(i=start1;i<=end1;i++)
  24. if(inorder[i]==val)
  25. break;//此处是根节点在中序遍历的位置
  26. int length=i-start1;//左子树元素个数
  27. Roo T -> left = help ( inorder start1 i - 1 postorder Start2 start2 + length - 1
  28. Roo T -> right = help ( inorder i + 1 end1 postorder start2 + length end2 - 1
  29. return root;
  30. }
  31. };






From for notes (Wiz)

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