题目:https://www.nowcoder.com/practice/4b91205483694f449f94c179883c1fef?tpId=40&tqId=21342&tPage=1&rp=1&ru=/ta/kaoyan&qru=/ta/kaoyan/question-ranking

主要是建树的代码还不太熟悉,说明自己这方面还有点薄弱

代码

  1. #include <cstdio>
  2. #include <string>
  3. #include <iostream>
  4. using namespace std;
  5. string input;
  6. int pos;
  7. struct Node{
  8. char name;
  9. Node * lchild;
  10. Node * rchild;
  11. }node;
  12. Node* create(){
  13. char c = input[pos++];
  14. if(c == '#'){
  15. return NULL;
  16. }
  17. Node *root = new Node;
  18. root->name = c;
  19. root->lchild = create();
  20. root->rchild = create();
  21. return root;
  22. }
  23. void PreOrder(Node *root){
  24. if(root == NULL) return;
  25. PreOrder(root->lchild);
  26. printf("%c ", root->name);
  27. PreOrder(root->rchild);
  28. return;
  29. }
  30. int main(){
  31. while(getline(cin, input), input != ""){
  32. pos = 0;
  33. Node *root = create();
  34. PreOrder(root);
  35. printf("\n");
  36. }
  37. }