题目:https://www.nowcoder.com/practice/b42cfd38923c4b72bde19b795e78bcb3?tpId=40&tqId=21555&tPage=2&rp=2&ru=/ta/kaoyan&qru=/ta/kaoyan/question-ranking

第十二行一开始没写搞得一直报错。

代码

  1. #include <cstdio>
  2. #include <vector>
  3. using namespace std;
  4. struct Node{
  5. int data;
  6. Node* lchild;
  7. Node* rchild;
  8. };
  9. void insert(Node* &root, int input){
  10. if(root == NULL){
  11. root = new Node;
  12. root->data = input;
  13. root->lchild = NULL;
  14. root->rchild = NULL;
  15. return;
  16. }
  17. if(input == root->data) return;
  18. else if(input > root->data){
  19. insert(root->rchild, input);
  20. }
  21. else {
  22. insert(root->lchild, input);
  23. }
  24. return;
  25. }
  26. void pre_order(Node *root){
  27. if(root == NULL) return;
  28. printf("%d ",root->data);
  29. pre_order(root->lchild);
  30. pre_order(root->rchild);
  31. }
  32. void in_order(Node *root){
  33. if(root == NULL) return;
  34. in_order(root->lchild);
  35. printf("%d ",root->data);
  36. in_order(root->rchild);
  37. }
  38. void post_order(Node *root){
  39. if(root == NULL) return;
  40. post_order(root->lchild);
  41. post_order(root->rchild);
  42. printf("%d ",root->data);
  43. }
  44. int main(){
  45. int n, input;
  46. while(scanf("%d", &n)!=EOF){
  47. Node *root = NULL;
  48. vector<int> input(n, 0);
  49. for(int i = 0; i < n; i++) scanf("%d", &input[i]);
  50. for(int i = 0; i < n; i++){
  51. insert(root, input[i]);
  52. }
  53. pre_order(root);
  54. printf("\n");
  55. in_order(root);
  56. printf("\n");
  57. post_order(root);
  58. printf("\n");
  59. }
  60. return 0;
  61. }