[关闭]
@zsh-o 2018-07-05T15:26:04.000000Z 字数 1319 阅读 898

由前序和中序唯一确定二叉树,并用层次遍历输出

算法


前遍历的第一个点是该树的根,然后根据其在中序遍历的位置确定左子树和右字数的个数,前序和中序的左右子树的节点都是相邻的,所以每次知道该中序和前序中相邻的段就能确定该树,层次遍历用一个队列表述

  1. /**
  2. * Created by zsh_o on 2018/7/5.
  3. * 由前序中序构造唯一二叉树
  4. * 11
  5. * 0 1 3 4 7 10 2 5 8 6 9
  6. * 3 1 7 10 4 1 5 8 2 9 6
  7. * */
  8. #include <iostream>
  9. using namespace std;
  10. struct TreeNode{
  11. int val;
  12. TreeNode* left;
  13. TreeNode* right;
  14. TreeNode(int value):val(value),left(NULL),right(NULL){}
  15. };
  16. const int MAXN = 10000;
  17. int Pre[MAXN];
  18. int IndexPre[MAXN];
  19. int In[MAXN];
  20. int IndexIn[MAXN];
  21. int N;
  22. TreeNode* build_tree(int pleft, int pright, int ileft, int iright){
  23. TreeNode* root = new TreeNode(Pre[pleft]); //前序第一个为根节点
  24. int r_i = IndexIn[Pre[pleft]]; // 根节点在中序的位置
  25. int n_left = r_i - ileft;
  26. int n_right = iright - r_i;
  27. if(n_left > 0){
  28. root->left = build_tree(pleft + 1, pleft + n_left, ileft, r_i - 1);
  29. }
  30. if(n_right > 0){
  31. root->right = build_tree(pright - n_right + 1, pright, r_i + 1, iright);
  32. }
  33. return root;
  34. }
  35. int main(){
  36. cin>>N;
  37. int t;
  38. for(int i=0; i<N; i++){
  39. cin>>t;
  40. Pre[i] = t;
  41. IndexPre[t] = i;
  42. }
  43. for(int i=0; i<N; i++){
  44. cin>>t;
  45. In[i] = t;
  46. IndexIn[t] = i;
  47. }
  48. TreeNode* root = build_tree(0, N-1, 0, N-1);
  49. // 层次遍历输出
  50. TreeNode* Queue[MAXN];
  51. int head = 0;
  52. int tail = 0;
  53. Queue[tail] = root;
  54. tail = (tail + 1) % MAXN;
  55. while(head != tail){
  56. int cn = (tail - head + MAXN) % MAXN;
  57. for(int i=0; i<cn; i++){
  58. TreeNode* t = Queue[head];
  59. head = (head + 1) % MAXN;
  60. cout<<t->val<<" ";
  61. if(t->left != NULL){
  62. Queue[tail] = t->left;
  63. tail = (tail + 1) % MAXN;
  64. }
  65. if(t->right != NULL){
  66. Queue[tail] = t->right;
  67. tail = (tail + 1) % MAXN;
  68. }
  69. }
  70. cout<<endl;
  71. }
  72. }

  1. Input:
  2. 11
  3. 0 1 3 4 7 10 2 5 8 6 9
  4. 3 1 7 10 4 0 5 8 2 9 6
  5. Output:
  6. 0
  7. 1 2
  8. 3 4 5 6
  9. 7 8 9
  10. 10
添加新批注
在作者公开此批注前,只有你和作者可见。
回复批注