PAT prepare this wrong

Update: 1115--

  • [1115 Counting Nodes in a BST:LIU]

    • within build function, declare a variable for the root address root =new node();, no node* root =new node();, this is to re-declare another variable.

      node* build(node* &root,int v) {
          if(root==NULL) {
              root =new node();//声明节点变量
              root->data=v;
              root->lchild=root->rchild=NULL;
          } else if(v<=root->data) { //左子树
              root->lchild=build(root->lchild,v);
          } else { //右子树
              root->rchild=build(root->rchild,v);
          }
      
          return root;
      }
      //main函数
      node* root=NULL;
      for(int i=0; i<N; i++) {
          scanf("%d",&v);
          root=build(root,v);
      }


  • [1115 Counting Nodes in a BST: My approach]

    • create () to create a root node, other nodes when inserted after cycling, attention Data [] is an index from 1 began. I have written in the wrong starting at 0, result = left 25 children and 25 while inserted in the root.

      //插入节点
      void insert(node* &root,int d) {
          if(root==NULL) {//若某个节点没有左、右孩子,则将data作为它的孩子
              root=newNode(d);
              return;
          }
          if(d<=root->dt) { //去左子树
              insert(root->lchild,d);
          } else//去右子树
              insert(root->rchild,d);
      
      }
      //构造BST
      node* create(int data[],int n) {//data节点数据,n节点个数
          node* root=newNode(data[0]);//创建根节点
      //  cout<<"root.data="<<root->dt<<endl;
          if(root==NULL) {
              cout<<"root是空的"<<endl;
          }
      
          for(int i=1; i<n; i++) {//根节点已经创建了,从1开始! 
              insert(root,data[i]);
          }
      
          return root;
      }

Guess you like

Origin www.cnblogs.com/musecho/p/12322052.html
PAT