c ++ 打印二进制
In this article, we’ll take a look at implementing a Binary Search Tree in C/C++.
在本文中,我们将介绍在C / C ++中实现二进制搜索树的方法。
A Binary Search Tree(BST) is a Binary Tree in which every element of a left sub-tree is less than the root node, and every element in the right sub-tree is greater than it.
二进制搜索树 ( BST )是一种二进制树,其中左子树的每个元素都小于根节点,而右子树中的每个元素都大于根节点。
This definition applies to every node in the tree, starting from the root node.
从根节点开始,此定义适用于树中的每个节点。
For example, the below figure shows a Binary Search Tree.
例如,下图显示了二进制搜索树。
Here, the left sub-tree from the root contains elements lesser than it, and the right sub-tree has those greater than it. This also applies to every node in the tree, as you can observe.
在这里,从根开始的左子树包含的元素要小于它,而右子树具有的元素要大于它。 如您所见,这也适用于树中的每个节点。
Due to this, BSTs are often called “sorted binary trees”, since an in-order traversal (refer to this article for what it means) will give a sorted list of elements.
由于这个原因,BST s的通常被称为“排序二叉树”,由于中序遍历(请参阅此文章是什么意思)会给元素的排序列表。
Let us now understand some of the concepts involved, before implementing them.
现在,让我们在实施之前理解其中涉及的一些概念。
在C / C ++中为二进制搜索树创建数据结构 (Create the Data Structures for the Binary Search Tree in C/C++)
Let’s write the structures and some helper functions for our BST.
让我们为BST编写结构和一些辅助函数。
Any Binary Search Tree node has a data
element, along with pointers to it’s left
and right
children. It also has a marker is_leaf
, to check if it’s a leaf node.
任何Binary Search Tree节点都有一个data
元素,以及指向其left
子元素和right
子元素的指针。 它还具有标记is_leaf
,以检查它是否是叶节点。
Let’s write our structure now
让我们现在写我们的结构
typedef struct TreeNode {
// TreeNode structure for the Binary Search Tree (BST)
// A BST has the left subtree being less than the root,
// while the right subtree is greater than the root
int data; // A Node contains data
struct TreeNode* left, *right; // As well as pointers to the left and right children
int is_leaf; // Check whether a node is a leaf node or not
}TreeNode;
Now, we’ll make a function to create a new tree node, that initializes the parameters.
现在,我们将创建一个用于创建新树节点的函数,以初始化参数。
TreeNode* make_treenode(int data) {
// Construct a treenode pointer using data
TreeNode* node = (TreeNode*) calloc (1, sizeof(TreeNode));
node->data = data;
node->left = node->right = NULL;
node->is_leaf = 1;
return node;
}
Let’s also write a function that frees our complete Binary Search Tree in C/C++ from memory.
我们还要编写一个函数,以从内存中释放C / C ++中完整的二进制搜索树。
void free_bst(TreeNode* root) {
// Frees the complete BST from memory
if (!root)
return;
free_bst(root->left);
free_bst(root->right);
free(root);
}
Let’s now move onto the insert_bst()
method, that inserts a node into the BST.
现在,让我们转到insert_bst()
方法,该方法将一个节点插入BST。
将数据插入二叉搜索树 (Inserting Data into a Binary Search Tree)
Any Binary Search Tree (BST) has the property that:
任何二进制搜索树( BST )具有以下特性:
- The left sub-tree has elements of less value than the root node 左子树的元素值小于根节点
- The right sub-tree has elements greater than the root node 右子树的元素大于根节点
So, if we want to insert a node, we must ensure that our node must have its correct position, by comparing the key of the node with the current root.
因此,如果要插入节点,则必须通过将节点的键与当前根进行比较来确保节点必须具有正确的位置。
To visualize how the insertion is being done, let’s take an example.
为了可视化插入的完成方式,我们来看一个例子。
Consider the below tree, with only one node.
考虑下面的树,其中只有一个节点。
Let’s insert 20 to this tree. Since 45 > 20, we must insert it to the left sub-tree. Since our sub-tree is empty, we can directly add to it.
让我们在这棵树中插入20。 由于45> 20,因此必须将其插入左侧的子树中。 由于子树为空,因此可以直接添加到它。
Now, let’s insert 15. Since 15 < 45, we insert to the left sub-tree and update the current root. Now again, we check with the current root (20). 15 < 20, so we again move to the left and insert it.
现在,我们插入15。由于15 <45,我们插入到左子树并更新当前根。 现在,再次检查当前根(20)。 15 <20,因此我们再次移至左侧并将其插入。
Let’s insert 60 now. Since 60 > 45, we insert to the right.
现在插入60。 由于60> 45,因此我们在右侧插入。
Similarly, you can insert the elements 40, 50 and 70 to get our final BST.
同样,您可以插入元素40、50和70以获取最终的BST。
The algorithm for insertion is as follows:
插入算法如下:
- Start at the root node of the tree. If it does not exist, simply make the new node as the root node and return it! 从树的根节点开始。 如果它不存在,只需将新节点作为根节点并返回它即可!
- Otherwise, we must compare the key of the node to be inserted and the key of the root. 否则,我们必须比较要插入的节点的密钥和根的密钥。
- If the key of the node is lesser than the root, we need to insert it to the left sub-tree 如果节点的键小于根,则需要将其插入到左子树中
- Otherwise, insert to its right sub-tree. 否则,请插入其右侧的子树。
Our method has the signature of:
我们的方法具有以下特征:
TreeNode* insert_bst(TreeNode* root, int data);
This takes the pointer to the root node and inserts data
into it.
这会将指针带到根节点,并将data
插入其中。
If the root node is NULL
(doesn’t exist), we simply create a new node using data
and assign it as the new root node.
如果根节点为NULL
(不存在),我们只需使用data
创建一个新节点并将其分配为新的根节点。
TreeNode* insert_bst(TreeNode* root, int data) {
// Inserts data into it's appropriate position
// in the BST
if (!root) {
// Make the root node
root = make_treenode(data);
return root;
}
else {
// TODO: Insert to the existing root
return root;
}
}
Let’s now move on to the else
part, if we need to insert it to an existing node. We simply follow the algorithm described above, with additional checks for the leaf node base case.
现在,如果需要将其插入到现有节点中,请继续进行else
部分。 我们只需遵循上述算法,并对叶节点基本情况进行额外检查。
The comments in the code should be self-explanatory. We insert to the left sub-tree if data
< root->data
and to the right, if data
> root->data
.
代码中的注释应该是不言自明的。 如果data
< root->data
,则在左侧子树插入;如果data
> root->data
,则在右侧子树插入。
TreeNode* insert_bst(TreeNode* root, int data) {
// Inserts data into it's appropriate position
// in the BST
if (!root) {
// Make the root node
root = make_treenode(data);
return root;
}
else {
// We need to insert to the existing root
TreeNode* node = make_treenode(data);
TreeNode* temp = root;
while (temp) {
if (temp->is_leaf) {
// Inserting at a leaf node
if (temp->data > data) {
// Insert to the left
temp->left = node;
temp->is_leaf = 0;
break;
}
else {
// Insert to the right
temp->right = node;
temp->is_leaf = 0;
break;
}
}
else {
// Non leaf node
if (temp->data > data) {
// Go to the left subtree
if (temp->left == NULL) {
// If the left subtree is empty, add it here
// and break, since we've finished insertion
temp->left = node;
break;
}
temp = temp->left;
}
else {
// Go to the right subtree
if (temp->right == NULL) {
// If the left subtree is empty, add it here
// and break, since we've finished insertion
temp->right = node;
break;
}
temp = temp->right;
}
}
}
}
return root;
}
Now we’ve completed our insert procedure! Let’s now quickly complete the search_bst()
function as well.
现在,我们已经完成了插入过程! 现在,让我们快速完成search_bst()
函数。
搜索二叉搜索树 (Searching a Binary Search Tree)
This is very straightforward. We simply move to the left/right sub-trees based on the key comparison. We stop if we either reach a NULL
node, or if the current root node key matches our target.
这很简单。 我们仅根据键比较移至左/右子树。 如果到达NULL
节点,或者当前根节点密钥与我们的目标匹配,我们将停止。
int search_bst(TreeNode* root, int target) {
// Searches for target in the BST
if (!root)
return 0;
if (root->data == target)
return 1;
else if (root->data > target)
return search_bst(root->left, target);
else
return search_bst(root->right, target);
return 0;
}
Now that we’ve implemented both insert and search, let’s test if our program works correctly as of now.
现在我们已经实现了插入和搜索,现在让我们测试一下程序是否可以正常工作。
I’ll post the complete code until now, with additional functions for printing the BST in an in-order traversal.
到目前为止,我将发布完整的代码,并附带用于按顺序遍历打印BST的附加功能。
/**
Code for https://journaldev.com article
Purpose: A Binary Search Tree Implementation
@author: Vijay Ramachandran
@date: 08-03-2020
*/
#include <stdio.h>
#include <stdlib.h>
typedef struct TreeNode {
// TreeNode structure for the Binary Search Tree (BST)
// A BST has the left subtree being less than the root,
// while the right subtree is greater than the root
int data; // A Node contains data
struct TreeNode* left, *right; // As well as pointers to the left and right children
int is_leaf; // Check whether a node is a leaf node or not
}TreeNode;
TreeNode* make_treenode(int data) {
// Construct a treenode pointer using data
TreeNode* node = (TreeNode*) calloc (1, sizeof(TreeNode));
node->data = data;
node->left = node->right = NULL;
node->is_leaf = 1;
return node;
}
TreeNode* insert_bst(TreeNode* root, int data) {
// Inserts data into it's appropriate position
// in the BST
if (!root) {
// Make the root node
root = make_treenode(data);
return root;
}
else {
// We need to insert to the existing root
TreeNode* node = make_treenode(data);
TreeNode* temp = root;
while (temp) {
if (temp->is_leaf) {
// Inserting at a leaf node
if (temp->data > data) {
// Insert to the left
temp->left = node;
temp->is_leaf = 0;
break;
}
else {
// Insert to the right
temp->right = node;
temp->is_leaf = 0;
break;
}
}
else {
// Non leaf node
if (temp->data > data) {
// Go to the left subtree
if (temp->left == NULL) {
// If the left subtree is empty, add it here
// and break, since we've finished insertion
temp->left = node;
break;
}
temp = temp->left;
}
else {
// Go to the right subtree
if (temp->right == NULL) {
// If the left subtree is empty, add it here
// and break, since we've finished insertion
temp->right = node;
break;
}
temp = temp->right;
}
}
}
}
return root;
}
int search_bst(TreeNode* root, int target) {
// Searches for target in the BST
if (!root)
return 0;
if (root->data == target)
return 1;
else if (root->data > target)
return search_bst(root->left, target);
else
return search_bst(root->right, target);
return 0;
}
void free_bst(TreeNode* root) {
// Frees the complete BST from memory
if (!root)
return;
free_bst(root->left);
free_bst(root->right);
free(root);
}
void print_search(TreeNode* root, int target) {
if (search_bst(root, target) == 1) {
printf("Value: %d found in the BST!\n", target);
}
else {
printf("Value: %d is not found in the BST.\n", target);
}
}
void print_bst(TreeNode* root) {
// Prints the BST in an inorder traversal
if (!root)
return;
print_bst(root->left);
printf("Node: %d -> ", root->data);
print_bst(root->right);
}
int main() {
// Driver function for performing Binary Search Tree
// operations
TreeNode* root = make_treenode(45);
root = insert_bst(root, 20);
root = insert_bst(root, 15);
root = insert_bst(root, 60);
root = insert_bst(root, 40);
root = insert_bst(root, 50);
root = insert_bst(root, 70);
print_bst(root);
printf("\n");
print_search(root, 15);
print_search(root, 70);
print_search(root, 35);
free_bst(root);
return 0;
}
Output
输出量
Node: 15 -> Node: 20 -> Node: 40 -> Node: 45 -> Node: 50 -> Node: 60 -> Node: 70 ->
Value: 15 found in the BST!
Value: 70 found in the BST!
Value: 35 is not found in the BST.
Alright! This seems to work as expected, and we do get the sorted list of elements by in-order traversal.
好的! 这似乎按预期工作,并且我们按顺序遍历得到了元素的排序列表。
Let’s now move onto the delete method.
现在让我们进入delete方法。
从二叉搜索树中删除 (Delete from a Binary Search Tree)
This one is a bit more tricky compared to the rest. Since the iterative version is less intuitive, we’ll present a recursive algorithm for this.
与其余的相比,这有点棘手。 由于迭代版本不太直观,因此我们将为此提供一种递归算法。
We have multiple cases for deletion. The below algorithm is the most commonly used version for deletion from a BST.
我们有多种情况需要删除。 以下算法是从BST中删除的最常用版本。
- If a node has no children, simply delete it from the tree. 如果节点没有子节点,只需将其从树中删除。
- Else, it has one child, remove the node and replace with its child. It doesn’t matter if it is the left or the right child. 否则,它有一个子节点,删除该节点并替换为其子节点。 是左孩子还是右孩子都没有关系。
- If it has 2 children, this case is a bit more tricky. Here, we don’t delete this node. Rather, we find the in-order successor of that node and remove that node instead, after copying the key to the current node. 如果它有2个孩子,这种情况比较棘手。 在这里,我们不删除该节点。 相反,我们将密钥复制到当前节点后,找到该节点的有序后继节点,并删除该节点。
The in-order successor of a node is the next node that comes after in the in-order traversal.
节点的有序后继是在有序遍历之后的下一个节点。
For example, the in-order successor of the root node (45), is the node 50, since it is the next node that is greater than it.
例如,根节点(45)的有序后继者是节点50,因为它是大于它的下一个节点。
Since it is the next node in the sorted order, it is the leftmost node in the right sub-tree of the node!
由于它是排序顺序中的下一个节点,因此它是该节点右子树中的最左节点!
TreeNode* get_inorder_successor(TreeNode* node) {
// Returns the inorder successor of the current node
// But this is simply the leftmost node in the right subtree!
// Assume that the right subtree of node exists
TreeNode* temp = node->right;
while(temp->left) {
temp = temp->left;
}
return temp;
}
This method will return the in-order successor of a node in a tree, assuming that a right sub-tree exists.
假设存在正确的子树,此方法将返回树中节点的有序后继。
Now, we can write our delete_bst()
method, using the above algorithm. The code is shown below.
现在,我们可以使用上述算法编写delete_bst()
方法。 代码如下所示。
TreeNode* delete_bst(TreeNode* root, int target) {
// Deletes the node corresponding to target, from the BST
if (!root)
return root;
else {
TreeNode* temp = root;
if (temp->data > target) {
// Search in the left subtree and delete there
root->left = delete_bst(root->left, target);
}
else if (temp->data < target) {
// Search in the right subtree and delete there
root->right = delete_bst(root->right, target);
}
else {
// We've found the node
if (temp->left == NULL) {
// No problem, as the left subtree is NULL
// Update the node to it's right subtree
// Even if it does not exist, it is the same!
// We simply need to free the temp node
TreeNode* del_node = temp;
temp = temp->right;
del_node->right = NULL;
free(del_node);
return temp;
}
else if (temp->right == NULL) {
// If the right subtree is NULL, take the same
// logic for the previous case
TreeNode* del_node = temp;
temp = temp->left;
del_node->left = NULL;
free(del_node);
return temp;
}
else {
// This node has two children. We need to find the inorder
// successor and copy the data to the current node.
TreeNode* inorder_successor = get_inorder_successor(temp);
temp->data = inorder_successor->data;
// Remove the inorder_successor node, since we've copied it's data
// to the current node
root->right = delete_bst(root->right, inorder_successor->data);
}
}
return root;
}
}
We’ve implemented our delete_bst()
method as well! So, I’ll now post the complete code below.
我们还实现了delete_bst()
方法! 因此,我现在将在下面发布完整的代码。
#include <stdio.h>
#include <stdlib.h>
typedef struct TreeNode {
// TreeNode structure for the Binary Search Tree (BST)
// A BST has the left subtree being less than the root,
// while the right subtree is greater than the root
int data; // A Node contains data
struct TreeNode* left, *right; // As well as pointers to the left and right children
int is_leaf; // Check whether a node is a leaf node or not
}TreeNode;
TreeNode* make_treenode(int data) {
// Construct a treenode pointer using data
TreeNode* node = (TreeNode*) calloc (1, sizeof(TreeNode));
node->data = data;
node->left = node->right = NULL;
node->is_leaf = 1;
return node;
}
TreeNode* insert_bst(TreeNode* root, int data) {
// Inserts data into it's appropriate position
// in the BST
if (!root) {
// Make the root node
root = make_treenode(data);
return root;
}
else {
// We need to insert to the existing root
TreeNode* node = make_treenode(data);
TreeNode* temp = root;
while (temp) {
if (temp->is_leaf) {
// Inserting at a leaf node
if (temp->data > data) {
// Insert to the left
temp->left = node;
temp->is_leaf = 0;
break;
}
else {
// Insert to the right
temp->right = node;
temp->is_leaf = 0;
break;
}
}
else {
// Non leaf node
if (temp->data > data) {
// Go to the left subtree
if (temp->left == NULL) {
// If the left subtree is empty, add it here
// and break, since we've finished insertion
temp->left = node;
break;
}
temp = temp->left;
}
else {
// Go to the right subtree
if (temp->right == NULL) {
// If the left subtree is empty, add it here
// and break, since we've finished insertion
temp->right = node;
break;
}
temp = temp->right;
}
}
}
}
return root;
}
int search_bst(TreeNode* root, int target) {
// Searches for target in the BST
if (!root)
return 0;
if (root->data == target)
return 1;
else if (root->data > target)
return search_bst(root->left, target);
else
return search_bst(root->right, target);
return 0;
}
TreeNode* get_inorder_successor(TreeNode* node) {
// Returns the inorder successor of the current node
// But this is simply the leftmost node in the right subtree!
// Assume that the right subtree of node exists
TreeNode* temp = node->right;
while(temp->left) {
temp = temp->left;
}
return temp;
}
TreeNode* delete_bst(TreeNode* root, int target) {
// Deletes the node corresponding to target, from the BST
if (!root)
return root;
else {
TreeNode* temp = root;
if (temp->data > target) {
// Search in the left subtree and delete there
root->left = delete_bst(root->left, target);
}
else if (temp->data < target) {
// Search in the right subtree and delete there
root->right = delete_bst(root->right, target);
}
else {
// We've found the node
if (temp->left == NULL) {
// No problem, as the left subtree is NULL
// Update the node to it's right subtree
// Even if it does not exist, it is the same!
// We simply need to free the temp node
TreeNode* del_node = temp;
temp = temp->right;
del_node->right = NULL;
free(del_node);
return temp;
}
else if (temp->right == NULL) {
// If the right subtree is NULL, take the same
// logic for the previous case
TreeNode* del_node = temp;
temp = temp->left;
del_node->left = NULL;
free(del_node);
return temp;
}
else {
// This node has two children. We need to find the inorder
// successor and copy the data to the current node.
TreeNode* inorder_successor = get_inorder_successor(temp);
temp->data = inorder_successor->data;
// Remove the inorder_successor node, since we've copied it's data
// to the current node
root->right = delete_bst(root->right, inorder_successor->data);
}
}
return root;
}
}
void free_bst(TreeNode* root) {
// Frees the complete BST from memory
if (!root)
return;
free_bst(root->left);
free_bst(root->right);
free(root);
}
void print_search(TreeNode* root, int target) {
if (search_bst(root, target) == 1) {
printf("Value: %d found in the BST!\n", target);
}
else {
printf("Value: %d is not found in the BST.\n", target);
}
}
void print_bst(TreeNode* root) {
// Prints the BST in an inorder traversal
if (!root)
return;
print_bst(root->left);
printf("Node: %d -> ", root->data);
print_bst(root->right);
}
int main() {
// Driver function for performing Binary Search Tree
// operations
TreeNode* root = make_treenode(45);
root = insert_bst(root, 20);
root = insert_bst(root, 15);
root = insert_bst(root, 60);
root = insert_bst(root, 40);
root = insert_bst(root, 50);
root = insert_bst(root, 70);
print_bst(root);
printf("\n");
print_search(root, 15);
print_search(root, 70);
print_search(root, 35);
root = delete_bst(root, 50);
printf("Deleted 50 from the BST\n");
print_bst(root);
printf("\n");
root = delete_bst(root, 45);
printf("Deleted 45 from the BST\n");
print_bst(root);
printf("\n");
free_bst(root);
return 0;
}
Output
输出量
Node: 15 -> Node: 20 -> Node: 40 -> Node: 45 -> Node: 50 -> Node: 60 -> Node: 70 ->
Value: 15 found in the BST!
Value: 70 found in the BST!
Value: 35 is not found in the BST.
Deleted 50 from the BST
Node: 15 -> Node: 20 -> Node: 40 -> Node: 45 -> Node: 60 -> Node: 70 ->
Deleted 45 from the BST
Node: 15 -> Node: 20 -> Node: 40 -> Node: 60 -> Node: 70 ->
Hooray! This seems to work as expected, after deleting 50
and 45
. We’ve finally completed all our procedures, and we’re done!
万岁! 删除50
和45
后,这似乎按预期工作。 我们终于完成了所有程序,我们完成了!
实施的时间复杂度 (Time Complexity of Implementation)
The time complexity of the main procedures are given in the below table
下表给出了主要程序的时间复杂度
Procedure | Time Complexity of Implementation |
insert_bst() | O(h) -> h is the height of the BST |
search_bst() | O(h) -> h is the height of the BST |
delete_bst | O(h) -> h is the height of the BST |
程序 | 实施的时间复杂度 |
insert_bst() | O(h) -> h是BST的高度 |
search_bst() | O(h) -> h是BST的高度 |
delete_bst | O(h) -> h是BST的高度 |
使用BST的缺点 (The disadvantage of using BSTs)
The problem with BSTs is that since the insertion can happen arbitrarily, the tree can become skewed, with the height of the BST being potentially proportional to the number of elements!
BST的问题在于,由于插入可以任意发生,因此树可能会倾斜,并且BST的高度可能与元素数量成正比!
So now, the insert, search, and delete operations are equivalent to O(n) in the absolute worst case, instead of the expected O(logn)
因此,现在,在绝对最坏的情况下,插入,搜索和删除操作等效于O(n) ,而不是预期的O(logn)
To avoid this problem, some modifications to the BST model were proposed, and a popular data structure is called the AVL Tree. We’ll give you more details in our upcoming article, so stay tuned!
为了避免这个问题,提出了对BST模型的一些修改,并且将一种流行的数据结构称为AVL树 。 我们将在即将到来的文章中为您提供更多详细信息,请继续关注!
下载代码 (Download the Code)
You can get the code through a Github Gist that I’ve uploaded. Feel free to ask any questions or provide suggestions in the comment section below!
您可以通过我上传的Github Gist获取代码。 欢迎在下面的评论部分中提出任何问题或提出建议!
结论 (Conclusion)
Hopefully, you’ve learned how you can implement the methods for inserting, search and deleting into a Binary Search Tree in C/C++.
希望您已经学会了如何在C / C ++中实现在二进制搜索树中插入,搜索和删除的方法。
Our next article on this series will focus on AVL Trees, which aims to eliminate the problem of encountering a skewed tree, so stay tuned!
我们在本系列的下一篇文章中将重点介绍AVL树,该树旨在消除遇到偏斜树的问题,请继续关注!
参考资料 (References)
- Wikipedia article on Binary Search Tree 维基百科关于二叉搜索树的文章
翻译自: https://www.journaldev.com/37018/binary-search-tree-in-c-plus-plus
c ++ 打印二进制