C++ 二叉搜索树(BST)的实现方法

时间:2021-08-01 07:45:46

废话不多说了,直接给大家贴代码了,具体代码如下所示:

?
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
class BST
{
public:
  struct Node
  {
    int key;//节点的key
    int value;//节点的value
    Node* left;
    Node *right;
    int N;//节点的叶子节点数目
    Node(int _key, int _value, int _N)
    {
      key = _key;
      value = _value;
      N = _N;
    }
  };
  BST();
  ~BST();
  void put(int key, int value);
  int get(int key);
  int deleteKey(int key);
private:
  Node* _deleteKey(int key, Node *x);
  Node* _deleteMin(Node *x);
  int size(Node *x);
  int _get(int key, Node* x);
  Node * _put(int key, int value,Node *x);
  Node * min(Node *x);
  Node* root;
};
inline int BST::size(Node * x)
{
  if (x == nullptr)return 0;
  return x->N;
}
int BST::_get(int key, Node * x)
{
  if (x == nullptr)return 0;
  if (x->key < key)_get(key, x->right);
  else if (x->key > key)_get(key, x->left);
  else {
    return x->value;
  }
  return 0;
}
BST::Node* BST::_put(int key, int value, Node * x)
{
  if (x == nullptr) {
    Node *tmp = new Node(key, value, 1);
    return tmp;
  }
  if (x->key > key) {
    x->left=_put(key, value, x->left);
  }
  else if (x->key < key) {
    x->right=_put(key, value, x->right);
  }
  else x->key = key;
  x->N = size(x->left) + size(x->right) + 1;
  return x;
}
BST::Node* BST::min(Node * x)
{
  if (x->left == nullptr)return x;
  return min(x->left);
}
BST::BST()
{
}
BST::~BST()
{
}
void BST::put(int key, int value)
{
  root=_put(key, value, root);
}
int BST::get(int key)
{
  return _get(key, root);
}
BST::Node* BST::_deleteKey(int key, Node * x)
{
  if (x->key > key)x->left = _deleteKey(key, x->left);
  else if (x->key < key)x->right = _deleteKey(key, x->right);
  else {
    if (x->left == nullptr)return x->right;
    else if (x->right == nullptr)return x->left;
    else {
      Node *tmp = x;
      x = min(tmp->right);
      x->left = tmp->left;
      x->right = _deleteMin(tmp->right);
    }
  }
  x->N = size(x->left) + size(x->right) + 1;
  return x;
}
BST::Node* BST::_deleteMin(Node * x)
{
  if (x->left == nullptr)return x->right;
  x->left = _deleteMin(x->left);
  x->N = size(x->left) + size(x->right) + 1;
  return x;
}
int BST::deleteKey(int key)
{
  return _get(key, root);
}

以上所述是小编给大家介绍的C++ 二叉搜索树(BST)的实现方法,希望对大家有所帮助,如果大家有任何疑问请给我留言,小编会及时回复大家的。在此也非常感谢大家对服务器之家网站的支持!