PAT甲级1151 LCA in a Binary Tree LCA+DFS

清疚 2023-02-21 06:51 124阅读 0赞

watermark_type_ZmFuZ3poZW5naGVpdGk_shadow_10_text_aHR0cHM6Ly9ibG9nLmNzZG4ubmV0L3dlaXhpbl80MjI0MDY2Nw_size_16_color_FFFFFF_t_70

LCA问题在常规树中的实现,思路和1143一样,本体主要要解决的就是递归子树边界的问题

我采用的map映射的方法,将中序遍历的结点值映射为下标位置,那么如果用下标来代替结点值的话,当前的树便是一颗bst树了

利用这个特性,比较映射值便可以判断左右子树的关系

  1. #include<iostream>
  2. #include<vector>
  3. #include<unordered_map>
  4. #include<cstdio>
  5. using namespace std;
  6. vector<int> pre,in;
  7. unordered_map<int,int> indexofbst;//映射的二叉搜索树下标
  8. void dfs(int root,int l,int r,int a,int b)//root为当前根结点在先序中下标
  9. {
  10. //if(l>r)return;//递归边界
  11. int ia=indexofbst[a],ib=indexofbst[b];//测试的点在中序中的下标
  12. int iroot=indexofbst[pre[root]];//根结点在中序下标
  13. if((ia<iroot&&ib>iroot)||(ia>iroot&&ib<iroot))//在根结点的两侧
  14. printf("LCA of %d and %d is %d.\n",a,b,pre[root]);
  15. else if(ia<iroot&&ib<iroot)//都在左子树
  16. dfs(root+1,l,iroot-1,a,b);
  17. else if(ia>iroot&&ib>iroot)//递归中序右子树区间
  18. dfs(root+iroot,iroot+1,r,a,b);
  19. else if(ia==iroot)printf("%d is an ancestor of %d.\n",a,b);
  20. else printf("%d is an ancestor of %d.\n",b,a);
  21. }
  22. int main()
  23. {
  24. int n,m;//n结点数,m测试样例数
  25. cin>>m>>n;
  26. pre.resize(n+1);
  27. in.resize(n+1);
  28. for(int i=1;i<=n;i++)
  29. {
  30. cin>>in[i];
  31. indexofbst[in[i]]=i;
  32. }
  33. for(int i=1;i<=n;i++)
  34. {
  35. cin>>pre[i];
  36. }
  37. for(int i=0;i<m;i++)
  38. {
  39. int a,b;
  40. cin>>a>>b;
  41. if(!indexofbst[a]&&!indexofbst[b])
  42. printf("ERROR: %d and %d are not found.\n",a,b);
  43. else if(!indexofbst[a])
  44. printf("ERROR: %d is not found.\n",a);
  45. else if(!indexofbst[b])
  46. printf("ERROR: %d is not found.\n",b);
  47. else
  48. {
  49. dfs(1,1,n,a,b);
  50. }
  51. }
  52. return 0;
  53. }

发表评论

表情:
评论列表 (有 0 条评论,124人围观)

还没有评论,来说两句吧...

相关阅读

    相关 PAT甲级LCA专题复习

    这个部分在《算法笔记》是没有的。 这种新背景的题目,如果之前没有接触过,那只能从普通的定义去解,即: 1.建树 2.找祖先,找到一致的就是最低公共祖先 例子:[hih