当前位置:   article > 正文

数据结构树与二叉树(4)树的括号表示法

数据结构树与二叉树(4)树的括号表示法

  1. #include <iostream>
  2. #include <stack>
  3. #include <queue>
  4. using namespace std;
  5. struct Node {
  6. char name;
  7. Node* child;
  8. Node* brother;
  9. Node(char str, Node* ch = nullptr, Node* br = nullptr) {
  10. name = str;
  11. child = ch;
  12. brother = br;
  13. }
  14. };
  15. int main()
  16. {
  17. string str;
  18. cin >> str;
  19. int mark = 0;
  20. stack<Node*> s;
  21. queue<Node*> q;
  22. Node* root;
  23. for (int i = 1; i < str.length() - 1; i++) {
  24. switch (str[i]) {
  25. case '(':
  26. mark = 1;
  27. break;
  28. case ')':
  29. s.pop();
  30. break;
  31. case ',':
  32. mark = 2;
  33. break;
  34. default:
  35. Node* p = new Node(str[i]);
  36. if (s.empty()) root = p;
  37. if (mark == 1)
  38. {
  39. Node* t = s.top();
  40. t->child = p;
  41. }
  42. if (mark == 2)
  43. {
  44. Node* t = s.top();
  45. t->brother = p;
  46. s.pop();
  47. }
  48. s.push(p);
  49. }
  50. }
  51. q.push(root);
  52. while (!q.empty()) {
  53. Node* t = q.front();
  54. cout << t->name;
  55. q.pop();
  56. if (t->child != nullptr) {
  57. t = t->child;
  58. while (t != nullptr) {
  59. q.push(t);
  60. t = t->brother;
  61. }
  62. }
  63. }
  64. return 0;
  65. }

声明:本文内容由网友自发贡献,不代表【wpsshop博客】立场,版权归原作者所有,本站不承担相应法律责任。如您发现有侵权的内容,请联系我们。转载请注明出处:https://www.wpsshop.cn/w/很楠不爱3/article/detail/233272
推荐阅读
相关标签
  

闽ICP备14008679号