|
马上注册,结交更多好友,享用更多功能^_^
您需要 登录 才可以下载或查看,没有账号?立即注册
x
我在写一个二叉查找树(BST),但是为什么不能用?(系统总是分配给x->left和x->right不可用的指针,这是为什么?)
- #if !defined (BST_H)
- #define BST_H
- template<class Index, class Value>
- class BST
- {
- private:
- struct Node
- {
- Node(Index k, Value v, int n)
- :key(k), val(v), N(n)
- {}
- Index key;
- Value val;
- Node *left, *right;
- int N;
- };
- Node *root = 0;
- public:
- int size()
- {
- return size(root);
- }
- Value get(Index key)
- {
- return get(root, key);
- }
- void put(Index key, Value val)
- { // Search for key. Update value if found; grow table if new.
- root = put(root, key, val);
- }
- private:
- int size(Node *x)
- {
- if(!x) return 0;
- else return x->N;
- }
-
- Value get(Node *x, Index key)
- { // Return value associated with key in the subtree rooted at x;
- // return null if key not present in subtree rooted at x.
- if (!x) return 0;
- int cmp = compare(key, x->key);
- if (cmp < 0) return get(x->left, key);
- else if (cmp > 0) return get(x->right, key);
- else return x->val;
- }
-
- Node* put(Node* x, Index key, Value val)
- {
- if(!x)
- {
- x = new Node(key, val, 1);
- return x;
- }
- int cmp = compare(key, x->key);
- if(cmp < 0)
- x->left = put(x->left, key, val);
- else if(cmp > 0)
- x->right = put(x->right, key, val);
- else
- x->val = val;
- x->N = size(x->left) + size(x->right) + 1;
- return x;
- }
-
- int compare(Index v, Index w) const
- {
- if(v > w) return 1;
- else if(v < w) return -1;
- return 0;
- }
- };
- #endif
复制代码
|
|