开发者

binary tree method

I have the following code:

#include <iostream>

using namespace std;

class BST{
public:
  int n,*v,vn;
  struct node {
    int val;
    node *left,*right;
    node (int v){ val=v; left=right=0;}
    void Print(开发者_运维技巧node *p){
       cout<<p->val;

       if (p->left){
           Print(p->left);
       }
       else if(p->right){
           Print(p->right);
       }
    }
  };  node *root;

  node *rinsert(node *p,int t){
     if (p==0){
        p=new node(t);
        n++;
     }
     else if (t<p->val){
        p->left=rinsert(p->left,t);
     }
     else if (t>p->val){
        p->right=rinsert(p->right,t);
     }

     return p;
  }
  void traverse(node *p){

    if (p==0) return;
    traverse(p->left);
    v[vn++]=p->val;
    traverse(p->right);
  }
  void print(){
    Print(root);
  }

public:
   BST(int maxelms,int maxval){
       root=0;
       n=0;
   }
   int size(){
      return n;
   }
   void insert(int v){
       root=rinsert(root,v);
   }
   void report(int *x){
       v=x;
       vn=0;
       traverse(root);
   }
};
int main(){
  BST bt(12,25);
  bt.insert(12);
  bt.insert(10);
  bt.insert(25);
  bt.insert(7);
  bt.insert(11);
  bt.insert(8);
  bt.insert(4);
  bt.insert(3);
  bt.insert(20);
  bt.insert(23);
  bt.insert(24);
  bt.insert(1);

  return 0;
}

The compiler says that Print() is undefined. Why? I have declared it inside class.


move your "void Print(node *p)" function outside the struct node definition


void Print(node *p){ --> static void Print(node *p){

else if(p->right){ --> if(p->right){

Print(root); --> node::Print(root);


You have two print methods:

BST::node::Print(node* p);
BST::print();

Capital Print is part of the node struct. Lowercase print is part of the BST class.

Problems you may encounter:

  • calling print outside the class. You would need to call: BST bt; bt.print();
  • calling Print outside the node class. You would need to call node n; n.Print(&n); Which would be somewhat silly. There's no need for Print to be part of the node class if it takes in a node.
  • calling Print() -- there's no such thing. There's print() and Print(node*) -- capitalization matters.

If that doesn't answer your question, please update your question with more information. Copy and paste the actual compiler error, and indicate which line gives you the error.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜