Guest User

Untitled

a guest
Apr 22nd, 2018
61
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 2.12 KB | None | 0 0
  1. //输入某二叉树的前序遍历和中序遍历的结果,请重建出该二叉树。假设输入的前序遍历和中序遍历的结果中都不含重复的数字。例如输入前序遍历序列{1,2,4,7,3,5,6,8}和中序遍历序列{4,7,2,1,5,3,8,6},则重建二叉树并返回。
  2.  
  3.  
  4.  
  5. struct TreeNode
  6. {
  7. int val;
  8. struct TreeNode *left;
  9. struct TreeNode *right;
  10. TreeNode(int x):val(x), left(NULL), right(NULL){}
  11. };
  12.  
  13.  
  14. void reConstructBinaryTreeFun(TreeNode *head, vector<int> pre, vector<int> vin)
  15. {
  16. if(pre.size() <= 1 && vin.size() <=1)//没有子节点了,结束
  17. {
  18. return ;
  19. }
  20.  
  21. vector<int> vecLeftVin, vecLeftPre;
  22. vector<int> vecRightVin, vecRightPre;
  23. size_t vecLeftVin_size = 0;
  24. vector<int>::iterator it;
  25. //前序遍历的第一个(即pre[0])为根节点
  26. it = find(vin.begin(), vin.end(), pre[0]); //找到根节点在中序遍历中的位置
  27. head->val = pre[0];
  28. //中序遍历根节点左边的,为左分支。
  29. if(it != vin.begin())
  30. {
  31. head->left = new TreeNode( *(it-1) );//中序遍历中,根节点左边第一个为根的左节点。
  32. vecLeftVin.assign(vin.begin(),it);//将中序遍历中根左边的部分放到新的vec中
  33. vecLeftVin_size = vecLeftVin.size();//记录大小
  34.  
  35. vecLeftPre.assign(pre.begin()+1, pre.begin()+1+vecLeftVin_size);//将前序遍历中根左边的部分放到新的vec中
  36. reConstructBinaryTreeFun(head->left,vecLeftPre, vecLeftVin);//继续递归分析
  37.  
  38. }
  39.  
  40. //中序遍历根节点右边的,为右分支。
  41.  
  42. if(it != vin.end()-1)
  43. {
  44. head->right = new TreeNode( *(it+1));//中序遍历中,根节点右边第一个为根的右节点。
  45. vecRightVin.assign(it+1, vin.end()); //将中序遍历中根右边的部分放到新的vec中
  46. size_t vecRightVin_size = vecRightVin.size();//记录大小
  47. vecRightPre.assign(pre.end()-vecRightVin_size, pre.end());//将前序遍历中根右边的部分放到新的vec中
  48. reConstructBinaryTreeFun(head->right, vecRightPre, vecRightVin);//继续递归分析
  49. }
  50.  
  51. }
  52.  
  53.  
  54. TreeNode* reConstructBinaryTree(vector<int> pre, vector<int> vin)
  55. {
  56. TreeNode * head ;
  57. head = new TreeNode(pre[0]);
  58.  
  59. reConstructBinaryTreeFun(head,pre,vin);
  60.  
  61. return head;
  62.  
  63. }
Add Comment
Please, Sign In to add comment