Guest User

Untitled

a guest
Apr 27th, 2018
68
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.09 KB | None | 0 0
  1. #include <assert.h>
  2. #include <ctype.h>
  3. #include <stdio.h>
  4. #include <deque>
  5.  
  6. struct Node
  7. {
  8. Node(char v) : val(v) {}
  9.  
  10. bool isOperator() const
  11. {
  12. return !isalnum(val);
  13. }
  14.  
  15. void print() const
  16. {
  17. if (isOperator())
  18. {
  19. printf("(");
  20. if (left)
  21. {
  22. left->print();
  23. }
  24. printf(" %c ", val);
  25. if (right)
  26. {
  27. right->print();
  28. }
  29. printf(")");
  30. }
  31. else
  32. {
  33. printf("%c", val);
  34. }
  35. }
  36.  
  37. char val;
  38. Node* left = NULL;
  39. Node* right = NULL;
  40. };
  41.  
  42. Node* buildTree(const char* expr)
  43. {
  44. Node* root = NULL;
  45. std::deque<Node**> queue;
  46. queue.push_back(&root);
  47. for (const char* p = expr; *p; ++p)
  48. {
  49. assert(!queue.empty());
  50. Node** curr = queue.front();
  51. queue.pop_front();
  52. assert(*curr == NULL);
  53. Node* n = new Node(*p);
  54. *curr = n;
  55. if (n->isOperator())
  56. {
  57. queue.push_back(&n->left);
  58. queue.push_back(&n->right);
  59. }
  60. }
  61. assert(queue.empty());
  62.  
  63. return root;
  64. }
  65.  
  66. int main(int argc, char* argv[])
  67. {
  68. Node* root = buildTree(argc > 1 ? argv[1] : "-+a+-abcd");
  69. root->print();
  70. printf("\n");
  71. }
Add Comment
Please, Sign In to add comment