二叉排序树

  • 测试用例中有重复数据,应忽略这些数据(题意)

    #include<iostream>
    #include <string>
    using namespace std;
    struct TreeNode{
      int s;
      TreeNode * left;
      TreeNode * right;
      TreeNode(int c):s(c),left(NULL), right(NULL){}
    };
    TreeNode* insert(TreeNode *pos, int x){
      if(pos == NULL){
          pos = new TreeNode(x);      
      } else if( x > pos->s ){
          pos->right = insert(pos->right, x);
      } else if( x < pos->s ){
          pos->left = insert(pos->left, x);
      }
      return pos;
    }
    void preorder(TreeNode *root){
      if(root == NULL) return;
      cout << root->s<< " ";
      preorder(root->left);
      preorder(root->right);
      return;
    }
    void inorder(TreeNode *root){
      if(root == NULL) return; 
      inorder(root->left);
      cout << root->s<< " ";
      inorder(root->right);
      return;
    }
    void postorder(TreeNode *root){
      if(root == NULL) return;
      postorder(root->left);
      postorder(root->right);
      cout << root->s << " ";
      return;
    }
    int main()
    {
      int n;
      while(cin >> n){
          TreeNode *root = NULL;
          for(int i = 0; i < n; i++){
              int t = 0; cin >> t;
              root = insert(root, t);
          }
          preorder(root); cout << endl;
          inorder(root); cout << endl;
          postorder(root); cout << endl;
    
      }
      return 0;
    }