Add the initial EN translation for C++ code (#1346)

This commit is contained in:
Yudong Jin
2024-05-06 13:31:46 +08:00
committed by GitHub
parent 9e4017b3fb
commit 8e60d12151
111 changed files with 6993 additions and 9 deletions

View File

@ -0,0 +1,6 @@
add_executable(avl_tree avl_tree.cpp)
add_executable(binary_search_tree binary_search_tree.cpp)
add_executable(binary_tree binary_tree.cpp)
add_executable(binary_tree_bfs binary_tree_bfs.cpp)
add_executable(binary_tree_dfs binary_tree_dfs.cpp)
add_executable(array_binary_tree array_binary_tree.cpp)

View File

@ -0,0 +1,137 @@
/**
* File: array_binary_tree.cpp
* Created Time: 2023-07-19
* Author: krahets (krahets@163.com)
*/
#include "../utils/common.hpp"
/* Array-based binary tree class */
class ArrayBinaryTree {
public:
/* Constructor */
ArrayBinaryTree(vector<int> arr) {
tree = arr;
}
/* List capacity */
int size() {
return tree.size();
}
/* Get the value of the node at index i */
int val(int i) {
// If index is out of bounds, return INT_MAX, representing a null
if (i < 0 || i >= size())
return INT_MAX;
return tree[i];
}
/* Get the index of the left child of the node at index i */
int left(int i) {
return 2 * i + 1;
}
/* Get the index of the right child of the node at index i */
int right(int i) {
return 2 * i + 2;
}
/* Get the index of the parent of the node at index i */
int parent(int i) {
return (i - 1) / 2;
}
/* Level-order traversal */
vector<int> levelOrder() {
vector<int> res;
// Traverse array
for (int i = 0; i < size(); i++) {
if (val(i) != INT_MAX)
res.push_back(val(i));
}
return res;
}
/* Pre-order traversal */
vector<int> preOrder() {
vector<int> res;
dfs(0, "pre", res);
return res;
}
/* In-order traversal */
vector<int> inOrder() {
vector<int> res;
dfs(0, "in", res);
return res;
}
/* Post-order traversal */
vector<int> postOrder() {
vector<int> res;
dfs(0, "post", res);
return res;
}
private:
vector<int> tree;
/* Depth-first traversal */
void dfs(int i, string order, vector<int> &res) {
// If it is an empty spot, return
if (val(i) == INT_MAX)
return;
// Pre-order traversal
if (order == "pre")
res.push_back(val(i));
dfs(left(i), order, res);
// In-order traversal
if (order == "in")
res.push_back(val(i));
dfs(right(i), order, res);
// Post-order traversal
if (order == "post")
res.push_back(val(i));
}
};
/* Driver Code */
int main() {
// Initialize binary tree
// Use INT_MAX to represent an empty spot nullptr
vector<int> arr = {1, 2, 3, 4, INT_MAX, 6, 7, 8, 9, INT_MAX, INT_MAX, 12, INT_MAX, INT_MAX, 15};
TreeNode *root = vectorToTree(arr);
cout << "\nInitialize binary tree\n";
cout << "Binary tree in array representation:\n";
printVector(arr);
cout << "Binary tree in linked list representation:\n";
printTree(root);
// Array-based binary tree class
ArrayBinaryTree abt(arr);
// Access node
int i = 1;
int l = abt.left(i), r = abt.right(i), p = abt.parent(i);
cout << "\nCurrent node's index is " << i << ", value = " << abt.val(i) << "\n";
cout << "Its left child's index is " << l << ", value = " << (l != INT_MAX ? to_string(abt.val(l)) : "nullptr") << "\n";
cout << "Its right child's index is " << r << ", value = " << (r != INT_MAX ? to_string(abt.val(r)) : "nullptr") << "\n";
cout << "Its parent's index is " << p << ", value = " << (p != INT_MAX ? to_string(abt.val(p)) : "nullptr") << "\n";
// Traverse tree
vector<int> res = abt.levelOrder();
cout << "\nLevel-order traversal is:";
printVector(res);
res = abt.preOrder();
cout << "Pre-order traversal is:";
printVector(res);
res = abt.inOrder();
cout << "In-order traversal is:";
printVector(res);
res = abt.postOrder();
cout << "Post-order traversal is:";
printVector(res);
return 0;
}

View File

@ -0,0 +1,233 @@
/**
* File: avl_tree.cpp
* Created Time: 2023-02-03
* Author: what-is-me (whatisme@outlook.jp)
*/
#include "../utils/common.hpp"
/* AVL tree */
class AVLTree {
private:
/* Update node height */
void updateHeight(TreeNode *node) {
// Node height equals the height of the tallest subtree + 1
node->height = max(height(node->left), height(node->right)) + 1;
}
/* Right rotation operation */
TreeNode *rightRotate(TreeNode *node) {
TreeNode *child = node->left;
TreeNode *grandChild = child->right;
// Rotate node to the right around child
child->right = node;
node->left = grandChild;
// Update node height
updateHeight(node);
updateHeight(child);
// Return the root of the subtree after rotation
return child;
}
/* Left rotation operation */
TreeNode *leftRotate(TreeNode *node) {
TreeNode *child = node->right;
TreeNode *grandChild = child->left;
// Rotate node to the left around child
child->left = node;
node->right = grandChild;
// Update node height
updateHeight(node);
updateHeight(child);
// Return the root of the subtree after rotation
return child;
}
/* Perform rotation operation to restore balance to the subtree */
TreeNode *rotate(TreeNode *node) {
// Get the balance factor of node
int _balanceFactor = balanceFactor(node);
// Left-leaning tree
if (_balanceFactor > 1) {
if (balanceFactor(node->left) >= 0) {
// Right rotation
return rightRotate(node);
} else {
// First left rotation then right rotation
node->left = leftRotate(node->left);
return rightRotate(node);
}
}
// Right-leaning tree
if (_balanceFactor < -1) {
if (balanceFactor(node->right) <= 0) {
// Left rotation
return leftRotate(node);
} else {
// First right rotation then left rotation
node->right = rightRotate(node->right);
return leftRotate(node);
}
}
// Balanced tree, no rotation needed, return
return node;
}
/* Recursively insert node (helper method) */
TreeNode *insertHelper(TreeNode *node, int val) {
if (node == nullptr)
return new TreeNode(val);
/* 1. Find insertion position and insert node */
if (val < node->val)
node->left = insertHelper(node->left, val);
else if (val > node->val)
node->right = insertHelper(node->right, val);
else
return node; // Do not insert duplicate nodes, return
updateHeight(node); // Update node height
/* 2. Perform rotation operation to restore balance to the subtree */
node = rotate(node);
// Return the root node of the subtree
return node;
}
/* Recursively remove node (helper method) */
TreeNode *removeHelper(TreeNode *node, int val) {
if (node == nullptr)
return nullptr;
/* 1. Find and remove the node */
if (val < node->val)
node->left = removeHelper(node->left, val);
else if (val > node->val)
node->right = removeHelper(node->right, val);
else {
if (node->left == nullptr || node->right == nullptr) {
TreeNode *child = node->left != nullptr ? node->left : node->right;
// Number of child nodes = 0, remove node and return
if (child == nullptr) {
delete node;
return nullptr;
}
// Number of child nodes = 1, remove node
else {
delete node;
node = child;
}
} else {
// Number of child nodes = 2, remove the next node in in-order traversal and replace the current node with it
TreeNode *temp = node->right;
while (temp->left != nullptr) {
temp = temp->left;
}
int tempVal = temp->val;
node->right = removeHelper(node->right, temp->val);
node->val = tempVal;
}
}
updateHeight(node); // Update node height
/* 2. Perform rotation operation to restore balance to the subtree */
node = rotate(node);
// Return the root node of the subtree
return node;
}
public:
TreeNode *root; // Root node
/* Get node height */
int height(TreeNode *node) {
// Empty node height is -1, leaf node height is 0
return node == nullptr ? -1 : node->height;
}
/* Get balance factor */
int balanceFactor(TreeNode *node) {
// Empty node balance factor is 0
if (node == nullptr)
return 0;
// Node balance factor = left subtree height - right subtree height
return height(node->left) - height(node->right);
}
/* Insert node */
void insert(int val) {
root = insertHelper(root, val);
}
/* Remove node */
void remove(int val) {
root = removeHelper(root, val);
}
/* Search node */
TreeNode *search(int val) {
TreeNode *cur = root;
// Loop find, break after passing leaf nodes
while (cur != nullptr) {
// Target node is in cur's right subtree
if (cur->val < val)
cur = cur->right;
// Target node is in cur's left subtree
else if (cur->val > val)
cur = cur->left;
// Found target node, break loop
else
break;
}
// Return target node
return cur;
}
/*Constructor*/
AVLTree() : root(nullptr) {
}
/*Destructor*/
~AVLTree() {
freeMemoryTree(root);
}
};
void testInsert(AVLTree &tree, int val) {
tree.insert(val);
cout << "\nAfter inserting node " << val << ", the AVL tree is" << endl;
printTree(tree.root);
}
void testRemove(AVLTree &tree, int val) {
tree.remove(val);
cout << "\nAfter removing node " << val << ", the AVL tree is" << endl;
printTree(tree.root);
}
/* Driver Code */
int main() {
/* Initialize empty AVL tree */
AVLTree avlTree;
/* Insert node */
// Notice how the AVL tree maintains balance after inserting nodes
testInsert(avlTree, 1);
testInsert(avlTree, 2);
testInsert(avlTree, 3);
testInsert(avlTree, 4);
testInsert(avlTree, 5);
testInsert(avlTree, 8);
testInsert(avlTree, 7);
testInsert(avlTree, 9);
testInsert(avlTree, 10);
testInsert(avlTree, 6);
/* Insert duplicate node */
testInsert(avlTree, 7);
/* Remove node */
// Notice how the AVL tree maintains balance after removing nodes
testRemove(avlTree, 8); // Remove node with degree 0
testRemove(avlTree, 5); // Remove node with degree 1
testRemove(avlTree, 4); // Remove node with degree 2
/* Search node */
TreeNode *node = avlTree.search(7);
cout << "\nThe found node object is " << node << ", node value =" << node->val << endl;
}

View File

@ -0,0 +1,170 @@
/**
* File: binary_search_tree.cpp
* Created Time: 2022-11-25
* Author: krahets (krahets@163.com)
*/
#include "../utils/common.hpp"
/* Binary search tree */
class BinarySearchTree {
private:
TreeNode *root;
public:
/* Constructor */
BinarySearchTree() {
// Initialize empty tree
root = nullptr;
}
/* Destructor */
~BinarySearchTree() {
freeMemoryTree(root);
}
/* Get binary tree root node */
TreeNode *getRoot() {
return root;
}
/* Search node */
TreeNode *search(int num) {
TreeNode *cur = root;
// Loop find, break after passing leaf nodes
while (cur != nullptr) {
// Target node is in cur's right subtree
if (cur->val < num)
cur = cur->right;
// Target node is in cur's left subtree
else if (cur->val > num)
cur = cur->left;
// Found target node, break loop
else
break;
}
// Return target node
return cur;
}
/* Insert node */
void insert(int num) {
// If tree is empty, initialize root node
if (root == nullptr) {
root = new TreeNode(num);
return;
}
TreeNode *cur = root, *pre = nullptr;
// Loop find, break after passing leaf nodes
while (cur != nullptr) {
// Found duplicate node, thus return
if (cur->val == num)
return;
pre = cur;
// Insertion position is in cur's right subtree
if (cur->val < num)
cur = cur->right;
// Insertion position is in cur's left subtree
else
cur = cur->left;
}
// Insert node
TreeNode *node = new TreeNode(num);
if (pre->val < num)
pre->right = node;
else
pre->left = node;
}
/* Remove node */
void remove(int num) {
// If tree is empty, return
if (root == nullptr)
return;
TreeNode *cur = root, *pre = nullptr;
// Loop find, break after passing leaf nodes
while (cur != nullptr) {
// Found node to be removed, break loop
if (cur->val == num)
break;
pre = cur;
// Node to be removed is in cur's right subtree
if (cur->val < num)
cur = cur->right;
// Node to be removed is in cur's left subtree
else
cur = cur->left;
}
// If no node to be removed, return
if (cur == nullptr)
return;
// Number of child nodes = 0 or 1
if (cur->left == nullptr || cur->right == nullptr) {
// When the number of child nodes = 0 / 1, child = nullptr / that child node
TreeNode *child = cur->left != nullptr ? cur->left : cur->right;
// Remove node cur
if (cur != root) {
if (pre->left == cur)
pre->left = child;
else
pre->right = child;
} else {
// If the removed node is the root, reassign the root
root = child;
}
// Free memory
delete cur;
}
// Number of child nodes = 2
else {
// Get the next node in in-order traversal of cur
TreeNode *tmp = cur->right;
while (tmp->left != nullptr) {
tmp = tmp->left;
}
int tmpVal = tmp->val;
// Recursively remove node tmp
remove(tmp->val);
// Replace cur with tmp
cur->val = tmpVal;
}
}
};
/* Driver Code */
int main() {
/* Initialize binary search tree */
BinarySearchTree *bst = new BinarySearchTree();
// Note that different insertion orders can result in various tree structures. This particular sequence creates a perfect binary tree
vector<int> nums = {8, 4, 12, 2, 6, 10, 14, 1, 3, 5, 7, 9, 11, 13, 15};
for (int num : nums) {
bst->insert(num);
}
cout << endl << "The initialized binary tree is\n" << endl;
printTree(bst->getRoot());
/* Search node */
TreeNode *node = bst->search(7);
cout << endl << "The found node object is " << node << ", node value =" << node->val << endl;
/* Insert node */
bst->insert(16);
cout << endl << "After inserting node 16, the binary tree is\n" << endl;
printTree(bst->getRoot());
/* Remove node */
bst->remove(1);
cout << endl << "After removing node 1, the binary tree is\n" << endl;
printTree(bst->getRoot());
bst->remove(2);
cout << endl << "After removing node 2, the binary tree is\n" << endl;
printTree(bst->getRoot());
bst->remove(4);
cout << endl << "After removing node 4, the binary tree is\n" << endl;
printTree(bst->getRoot());
// Free memory
delete bst;
return 0;
}

View File

@ -0,0 +1,43 @@
/**
* File: binary_tree.cpp
* Created Time: 2022-11-25
* Author: krahets (krahets@163.com)
*/
#include "../utils/common.hpp"
/* Driver Code */
int main() {
/* Initialize binary tree */
// Initialize node
TreeNode *n1 = new TreeNode(1);
TreeNode *n2 = new TreeNode(2);
TreeNode *n3 = new TreeNode(3);
TreeNode *n4 = new TreeNode(4);
TreeNode *n5 = new TreeNode(5);
// Construct node references (pointers)
n1->left = n2;
n1->right = n3;
n2->left = n4;
n2->right = n5;
cout << endl << "Initialize binary tree\n" << endl;
printTree(n1);
/* Insert and remove nodes */
TreeNode *P = new TreeNode(0);
// Insert node P between n1 -> n2
n1->left = P;
P->left = n2;
cout << endl << "After inserting node P\n" << endl;
printTree(n1);
// Remove node P
n1->left = n2;
delete P; // Free memory
cout << endl << "After removing node P\n" << endl;
printTree(n1);
// Free memory
freeMemoryTree(n1);
return 0;
}

View File

@ -0,0 +1,42 @@
/**
* File: binary_tree_bfs.cpp
* Created Time: 2022-11-25
* Author: krahets (krahets@163.com)
*/
#include "../utils/common.hpp"
/* Level-order traversal */
vector<int> levelOrder(TreeNode *root) {
// Initialize queue, add root node
queue<TreeNode *> queue;
queue.push(root);
// Initialize a list to store the traversal sequence
vector<int> vec;
while (!queue.empty()) {
TreeNode *node = queue.front();
queue.pop(); // Queue dequeues
vec.push_back(node->val); // Save node value
if (node->left != nullptr)
queue.push(node->left); // Left child node enqueues
if (node->right != nullptr)
queue.push(node->right); // Right child node enqueues
}
return vec;
}
/* Driver Code */
int main() {
/* Initialize binary tree */
// Use a specific function to convert an array into a binary tree
TreeNode *root = vectorToTree(vector<int>{1, 2, 3, 4, 5, 6, 7});
cout << endl << "Initialize binary tree\n" << endl;
printTree(root);
/* Level-order traversal */
vector<int> vec = levelOrder(root);
cout << endl << "Sequence of nodes in level-order traversal = ";
printVector(vec);
return 0;
}

View File

@ -0,0 +1,69 @@
/**
* File: binary_tree_dfs.cpp
* Created Time: 2022-11-25
* Author: krahets (krahets@163.com)
*/
#include "../utils/common.hpp"
// Initialize the list for storing traversal sequences
vector<int> vec;
/* Pre-order traversal */
void preOrder(TreeNode *root) {
if (root == nullptr)
return;
// Visit priority: root node -> left subtree -> right subtree
vec.push_back(root->val);
preOrder(root->left);
preOrder(root->right);
}
/* In-order traversal */
void inOrder(TreeNode *root) {
if (root == nullptr)
return;
// Visit priority: left subtree -> root node -> right subtree
inOrder(root->left);
vec.push_back(root->val);
inOrder(root->right);
}
/* Post-order traversal */
void postOrder(TreeNode *root) {
if (root == nullptr)
return;
// Visit priority: left subtree -> right subtree -> root node
postOrder(root->left);
postOrder(root->right);
vec.push_back(root->val);
}
/* Driver Code */
int main() {
/* Initialize binary tree */
// Use a specific function to convert an array into a binary tree
TreeNode *root = vectorToTree(vector<int>{1, 2, 3, 4, 5, 6, 7});
cout << endl << "Initialize binary tree\n" << endl;
printTree(root);
/* Pre-order traversal */
vec.clear();
preOrder(root);
cout << endl << "Sequence of nodes in pre-order traversal = ";
printVector(vec);
/* In-order traversal */
vec.clear();
inOrder(root);
cout << endl << "Sequence of nodes in in-order traversal = ";
printVector(vec);
/* Post-order traversal */
vec.clear();
postOrder(root);
cout << endl << "Sequence of nodes in post-order traversal = ";
printVector(vec);
return 0;
}