Translate all code to English (#1836)

* Review the EN heading format.

* Fix pythontutor headings.

* Fix pythontutor headings.

* bug fixes

* Fix headings in **/summary.md

* Revisit the CN-to-EN translation for Python code using Claude-4.5

* Revisit the CN-to-EN translation for Java code using Claude-4.5

* Revisit the CN-to-EN translation for Cpp code using Claude-4.5.

* Fix the dictionary.

* Fix cpp code translation for the multipart strings.

* Translate Go code to English.

* Update workflows to test EN code.

* Add EN translation for C.

* Add EN translation for CSharp.

* Add EN translation for Swift.

* Trigger the CI check.

* Revert.

* Update en/hash_map.md

* Add the EN version of Dart code.

* Add the EN version of Kotlin code.

* Add missing code files.

* Add the EN version of JavaScript code.

* Add the EN version of TypeScript code.

* Fix the workflows.

* Add the EN version of Ruby code.

* Add the EN version of Rust code.

* Update the CI check for the English version  code.

* Update Python CI check.

* Fix cmakelists for en/C code.

* Fix Ruby comments
This commit is contained in:
Yudong Jin
2025-12-31 07:44:52 +08:00
committed by GitHub
parent 45e1295241
commit 2778a6f9c7
1284 changed files with 71557 additions and 3275 deletions
@@ -0,0 +1,192 @@
/*
* File: array_binary_tree.rs
* Created Time: 2023-07-25
* Author: night-cruise (2586447362@qq.com)
*/
use hello_algo_rust::include::{print_util, tree_node};
/* Binary tree class represented by array */
struct ArrayBinaryTree {
tree: Vec<Option<i32>>,
}
impl ArrayBinaryTree {
/* Constructor */
fn new(arr: Vec<Option<i32>>) -> Self {
Self { tree: arr }
}
/* List capacity */
fn size(&self) -> i32 {
self.tree.len() as i32
}
/* Get value of node at index i */
fn val(&self, i: i32) -> Option<i32> {
// If index is out of bounds, return None, representing empty position
if i < 0 || i >= self.size() {
None
} else {
self.tree[i as usize]
}
}
/* Get index of left child node of node at index i */
fn left(&self, i: i32) -> i32 {
2 * i + 1
}
/* Get index of right child node of node at index i */
fn right(&self, i: i32) -> i32 {
2 * i + 2
}
/* Get index of parent node of node at index i */
fn parent(&self, i: i32) -> i32 {
(i - 1) / 2
}
/* Level-order traversal */
fn level_order(&self) -> Vec<i32> {
self.tree.iter().filter_map(|&x| x).collect()
}
/* Depth-first traversal */
fn dfs(&self, i: i32, order: &'static str, res: &mut Vec<i32>) {
if self.val(i).is_none() {
return;
}
let val = self.val(i).unwrap();
// Preorder traversal
if order == "pre" {
res.push(val);
}
self.dfs(self.left(i), order, res);
// Inorder traversal
if order == "in" {
res.push(val);
}
self.dfs(self.right(i), order, res);
// Postorder traversal
if order == "post" {
res.push(val);
}
}
/* Preorder traversal */
fn pre_order(&self) -> Vec<i32> {
let mut res = vec![];
self.dfs(0, "pre", &mut res);
res
}
/* Inorder traversal */
fn in_order(&self) -> Vec<i32> {
let mut res = vec![];
self.dfs(0, "in", &mut res);
res
}
/* Postorder traversal */
fn post_order(&self) -> Vec<i32> {
let mut res = vec![];
self.dfs(0, "post", &mut res);
res
}
}
/* Driver Code */
fn main() {
// Initialize binary tree
// Here we use a function to generate a binary tree directly from an array
let arr = vec![
Some(1),
Some(2),
Some(3),
Some(4),
None,
Some(6),
Some(7),
Some(8),
Some(9),
None,
None,
Some(12),
None,
None,
Some(15),
];
let root = tree_node::vec_to_tree(arr.clone()).unwrap();
println!("\nInitialize binary tree\n");
println!("Array representation of binary tree:");
println!(
"[{}]",
arr.iter()
.map(|&val| if let Some(val) = val {
format!("{val}")
} else {
"null".to_string()
})
.collect::<Vec<String>>()
.join(", ")
);
println!("Linked list representation of binary tree:");
print_util::print_tree(&root);
// Binary tree class represented by array
let abt = ArrayBinaryTree::new(arr);
// Access node
let i = 1;
let l = abt.left(i);
let r = abt.right(i);
let p = abt.parent(i);
println!(
"\nCurrent node index is {}, value is {}",
i,
if let Some(val) = abt.val(i) {
format!("{val}")
} else {
"null".to_string()
}
);
println!(
"Left child index is {}, value is {}",
l,
if let Some(val) = abt.val(l) {
format!("{val}")
} else {
"null".to_string()
}
);
println!(
"Right child index is {}, value is {}",
r,
if let Some(val) = abt.val(r) {
format!("{val}")
} else {
"null".to_string()
}
);
println!(
"Parent node index is {}, value is {}",
p,
if let Some(val) = abt.val(p) {
format!("{val}")
} else {
"null".to_string()
}
);
// Traverse tree
let mut res = abt.level_order();
println!("\nLevel-order traversal is: {:?}", res);
res = abt.pre_order();
println!("Pre-order traversal is: {:?}", res);
res = abt.in_order();
println!("In-order traversal is: {:?}", res);
res = abt.post_order();
println!("Post-order traversal is: {:?}", res);
}
+297
View File
@@ -0,0 +1,297 @@
/*
* File: avl_tree.rs
* Created Time: 2023-07-14
* Author: night-cruise (2586447362@qq.com)
*/
use hello_algo_rust::include::{print_util, TreeNode};
use std::cell::RefCell;
use std::cmp::Ordering;
use std::rc::Rc;
type OptionTreeNodeRc = Option<Rc<RefCell<TreeNode>>>;
/* AVL tree */
struct AVLTree {
root: OptionTreeNodeRc, // Root node
}
impl AVLTree {
/* Constructor */
fn new() -> Self {
Self { root: None }
}
/* Get node height */
fn height(node: OptionTreeNodeRc) -> i32 {
// Empty node height is -1, leaf node height is 0
match node {
Some(node) => node.borrow().height,
None => -1,
}
}
/* Update node height */
fn update_height(node: OptionTreeNodeRc) {
if let Some(node) = node {
let left = node.borrow().left.clone();
let right = node.borrow().right.clone();
// Node height equals the height of the tallest subtree + 1
node.borrow_mut().height = std::cmp::max(Self::height(left), Self::height(right)) + 1;
}
}
/* Get balance factor */
fn balance_factor(node: OptionTreeNodeRc) -> i32 {
match node {
// Empty node balance factor is 0
None => 0,
// Node balance factor = left subtree height - right subtree height
Some(node) => {
Self::height(node.borrow().left.clone()) - Self::height(node.borrow().right.clone())
}
}
}
/* Right rotation operation */
fn right_rotate(node: OptionTreeNodeRc) -> OptionTreeNodeRc {
match node {
Some(node) => {
let child = node.borrow().left.clone().unwrap();
let grand_child = child.borrow().right.clone();
// Using child as pivot, rotate node to the right
child.borrow_mut().right = Some(node.clone());
node.borrow_mut().left = grand_child;
// Update node height
Self::update_height(Some(node));
Self::update_height(Some(child.clone()));
// Return root node of subtree after rotation
Some(child)
}
None => None,
}
}
/* Left rotation operation */
fn left_rotate(node: OptionTreeNodeRc) -> OptionTreeNodeRc {
match node {
Some(node) => {
let child = node.borrow().right.clone().unwrap();
let grand_child = child.borrow().left.clone();
// Using child as pivot, rotate node to the left
child.borrow_mut().left = Some(node.clone());
node.borrow_mut().right = grand_child;
// Update node height
Self::update_height(Some(node));
Self::update_height(Some(child.clone()));
// Return root node of subtree after rotation
Some(child)
}
None => None,
}
}
/* Perform rotation operation to restore balance to this subtree */
fn rotate(node: OptionTreeNodeRc) -> OptionTreeNodeRc {
// Get balance factor of node
let balance_factor = Self::balance_factor(node.clone());
// Left-leaning tree
if balance_factor > 1 {
let node = node.unwrap();
if Self::balance_factor(node.borrow().left.clone()) >= 0 {
// Right rotation
Self::right_rotate(Some(node))
} else {
// First left rotation then right rotation
let left = node.borrow().left.clone();
node.borrow_mut().left = Self::left_rotate(left);
Self::right_rotate(Some(node))
}
}
// Right-leaning tree
else if balance_factor < -1 {
let node = node.unwrap();
if Self::balance_factor(node.borrow().right.clone()) <= 0 {
// Left rotation
Self::left_rotate(Some(node))
} else {
// First right rotation then left rotation
let right = node.borrow().right.clone();
node.borrow_mut().right = Self::right_rotate(right);
Self::left_rotate(Some(node))
}
} else {
// Balanced tree, no rotation needed, return directly
node
}
}
/* Insert node */
fn insert(&mut self, val: i32) {
self.root = Self::insert_helper(self.root.clone(), val);
}
/* Recursively insert node (helper method) */
fn insert_helper(node: OptionTreeNodeRc, val: i32) -> OptionTreeNodeRc {
match node {
Some(mut node) => {
/* 1. Find insertion position and insert node */
match {
let node_val = node.borrow().val;
node_val
}
.cmp(&val)
{
Ordering::Greater => {
let left = node.borrow().left.clone();
node.borrow_mut().left = Self::insert_helper(left, val);
}
Ordering::Less => {
let right = node.borrow().right.clone();
node.borrow_mut().right = Self::insert_helper(right, val);
}
Ordering::Equal => {
return Some(node); // Duplicate node not inserted, return directly
}
}
Self::update_height(Some(node.clone())); // Update node height
/* 2. Perform rotation operation to restore balance to this subtree */
node = Self::rotate(Some(node)).unwrap();
// Return root node of subtree
Some(node)
}
None => Some(TreeNode::new(val)),
}
}
/* Remove node */
fn remove(&self, val: i32) {
Self::remove_helper(self.root.clone(), val);
}
/* Recursively delete node (helper method) */
fn remove_helper(node: OptionTreeNodeRc, val: i32) -> OptionTreeNodeRc {
match node {
Some(mut node) => {
/* 1. Find node and delete */
if val < node.borrow().val {
let left = node.borrow().left.clone();
node.borrow_mut().left = Self::remove_helper(left, val);
} else if val > node.borrow().val {
let right = node.borrow().right.clone();
node.borrow_mut().right = Self::remove_helper(right, val);
} else if node.borrow().left.is_none() || node.borrow().right.is_none() {
let child = if node.borrow().left.is_some() {
node.borrow().left.clone()
} else {
node.borrow().right.clone()
};
match child {
// Number of child nodes = 0, delete node directly and return
None => {
return None;
}
// Number of child nodes = 1, delete node directly
Some(child) => node = child,
}
} else {
// Number of child nodes = 2, delete the next node in inorder traversal and replace current node with it
let mut temp = node.borrow().right.clone().unwrap();
loop {
let temp_left = temp.borrow().left.clone();
if temp_left.is_none() {
break;
}
temp = temp_left.unwrap();
}
let right = node.borrow().right.clone();
node.borrow_mut().right = Self::remove_helper(right, temp.borrow().val);
node.borrow_mut().val = temp.borrow().val;
}
Self::update_height(Some(node.clone())); // Update node height
/* 2. Perform rotation operation to restore balance to this subtree */
node = Self::rotate(Some(node)).unwrap();
// Return root node of subtree
Some(node)
}
None => None,
}
}
/* Search node */
fn search(&self, val: i32) -> OptionTreeNodeRc {
let mut cur = self.root.clone();
// Loop search, exit after passing leaf node
while let Some(current) = cur.clone() {
match current.borrow().val.cmp(&val) {
// Target node is in cur's right subtree
Ordering::Less => {
cur = current.borrow().right.clone();
}
// Target node is in cur's left subtree
Ordering::Greater => {
cur = current.borrow().left.clone();
}
// Found target node, exit loop
Ordering::Equal => {
break;
}
}
}
// Return target node
cur
}
}
/* Driver Code */
fn main() {
fn test_insert(tree: &mut AVLTree, val: i32) {
tree.insert(val);
println!("\nAfter inserting node {}, AVL tree is", val);
print_util::print_tree(&tree.root.clone().unwrap());
}
fn test_remove(tree: &mut AVLTree, val: i32) {
tree.remove(val);
println!("\nAfter deleting node {}, AVL tree is", val);
print_util::print_tree(&tree.root.clone().unwrap());
}
/* Please pay attention to how the AVL tree maintains balance after inserting nodes */
let mut avl_tree = AVLTree::new();
/* Insert node */
// Delete nodes
test_insert(&mut avl_tree, 1);
test_insert(&mut avl_tree, 2);
test_insert(&mut avl_tree, 3);
test_insert(&mut avl_tree, 4);
test_insert(&mut avl_tree, 5);
test_insert(&mut avl_tree, 8);
test_insert(&mut avl_tree, 7);
test_insert(&mut avl_tree, 9);
test_insert(&mut avl_tree, 10);
test_insert(&mut avl_tree, 6);
/* Please pay attention to how the AVL tree maintains balance after deleting nodes */
test_insert(&mut avl_tree, 7);
/* Remove node */
// Delete node with degree 1
test_remove(&mut avl_tree, 8); // Delete node with degree 2
test_remove(&mut avl_tree, 5); // Remove node with degree 1
test_remove(&mut avl_tree, 4); // Remove node with degree 2
/* Search node */
let node = avl_tree.search(7);
if let Some(node) = node {
println!(
"\nFound node object is {:?}, node value = {}",
&*node.borrow(),
node.borrow().val
);
}
}
@@ -0,0 +1,195 @@
/*
* File: binary_search_tree.rs
* Created Time: 2023-04-20
* Author: xBLACKICEx (xBLACKICE@outlook.com)、night-cruise (2586447362@qq.com)
*/
use hello_algo_rust::include::print_util;
use std::cell::RefCell;
use std::cmp::Ordering;
use std::rc::Rc;
use hello_algo_rust::include::TreeNode;
type OptionTreeNodeRc = Option<Rc<RefCell<TreeNode>>>;
/* Binary search tree */
pub struct BinarySearchTree {
root: OptionTreeNodeRc,
}
impl BinarySearchTree {
/* Constructor */
pub fn new() -> Self {
// Initialize empty tree
Self { root: None }
}
/* Get binary tree root node */
pub fn get_root(&self) -> OptionTreeNodeRc {
self.root.clone()
}
/* Search node */
pub fn search(&self, num: i32) -> OptionTreeNodeRc {
let mut cur = self.root.clone();
// Loop search, exit after passing leaf node
while let Some(node) = cur.clone() {
match num.cmp(&node.borrow().val) {
// Target node is in cur's right subtree
Ordering::Greater => cur = node.borrow().right.clone(),
// Target node is in cur's left subtree
Ordering::Less => cur = node.borrow().left.clone(),
// Found target node, exit loop
Ordering::Equal => break,
}
}
// Return target node
cur
}
/* Insert node */
pub fn insert(&mut self, num: i32) {
// If tree is empty, initialize root node
if self.root.is_none() {
self.root = Some(TreeNode::new(num));
return;
}
let mut cur = self.root.clone();
let mut pre = None;
// Loop search, exit after passing leaf node
while let Some(node) = cur.clone() {
match num.cmp(&node.borrow().val) {
// Found duplicate node, return directly
Ordering::Equal => return,
// Insertion position is in cur's right subtree
Ordering::Greater => {
pre = cur.clone();
cur = node.borrow().right.clone();
}
// Insertion position is in cur's left subtree
Ordering::Less => {
pre = cur.clone();
cur = node.borrow().left.clone();
}
}
}
// Insert node
let pre = pre.unwrap();
let node = Some(TreeNode::new(num));
if num > pre.borrow().val {
pre.borrow_mut().right = node;
} else {
pre.borrow_mut().left = node;
}
}
/* Remove node */
pub fn remove(&mut self, num: i32) {
// If tree is empty, return directly
if self.root.is_none() {
return;
}
let mut cur = self.root.clone();
let mut pre = None;
// Loop search, exit after passing leaf node
while let Some(node) = cur.clone() {
match num.cmp(&node.borrow().val) {
// Found node to delete, exit loop
Ordering::Equal => break,
// Node to delete is in cur's right subtree
Ordering::Greater => {
pre = cur.clone();
cur = node.borrow().right.clone();
}
// Node to delete is in cur's left subtree
Ordering::Less => {
pre = cur.clone();
cur = node.borrow().left.clone();
}
}
}
// If no node to delete, return directly
if cur.is_none() {
return;
}
let cur = cur.unwrap();
let (left_child, right_child) = (cur.borrow().left.clone(), cur.borrow().right.clone());
match (left_child.clone(), right_child.clone()) {
// Number of child nodes = 0 or 1
(None, None) | (Some(_), None) | (None, Some(_)) => {
// When number of child nodes = 0 / 1, child = nullptr / that child node
let child = left_child.or(right_child);
let pre = pre.unwrap();
// Delete node cur
if !Rc::ptr_eq(&cur, self.root.as_ref().unwrap()) {
let left = pre.borrow().left.clone();
if left.is_some() && Rc::ptr_eq(left.as_ref().unwrap(), &cur) {
pre.borrow_mut().left = child;
} else {
pre.borrow_mut().right = child;
}
} else {
// If deleted node is root node, reassign root node
self.root = child;
}
}
// Number of child nodes = 2
(Some(_), Some(_)) => {
// Get next node of cur in inorder traversal
let mut tmp = cur.borrow().right.clone();
while let Some(node) = tmp.clone() {
if node.borrow().left.is_some() {
tmp = node.borrow().left.clone();
} else {
break;
}
}
let tmp_val = tmp.unwrap().borrow().val;
// Recursively delete node tmp
self.remove(tmp_val);
// Replace cur with tmp
cur.borrow_mut().val = tmp_val;
}
}
}
}
/* Driver Code */
fn main() {
/* Initialize binary search tree */
let mut bst = BinarySearchTree::new();
// Please note that different insertion orders will generate different binary trees, this sequence can generate a perfect binary tree
let nums = [8, 4, 12, 2, 6, 10, 14, 1, 3, 5, 7, 9, 11, 13, 15];
for &num in &nums {
bst.insert(num);
}
println!("\nInitialized binary tree is\n");
print_util::print_tree(bst.get_root().as_ref().unwrap());
/* Search node */
let node = bst.search(7);
println!(
"\nFound node object is {:?}, node value = {}",
node.clone().unwrap(),
node.clone().unwrap().borrow().val
);
/* Insert node */
bst.insert(16);
println!("\nAfter inserting node 16, binary tree is\n");
print_util::print_tree(bst.get_root().as_ref().unwrap());
/* Remove node */
bst.remove(1);
println!("\nAfter removing node 1, binary tree is\n");
print_util::print_tree(bst.get_root().as_ref().unwrap());
bst.remove(2);
println!("\nAfter removing node 2, binary tree is\n");
print_util::print_tree(bst.get_root().as_ref().unwrap());
bst.remove(4);
println!("\nAfter removing node 4, binary tree is\n");
print_util::print_tree(bst.get_root().as_ref().unwrap());
}
+38
View File
@@ -0,0 +1,38 @@
/**
* File: binary_tree.rs
* Created Time: 2023-02-27
* Author: xBLACKICEx (xBLACKICE@outlook.com)
*/
use std::rc::Rc;
use hello_algo_rust::include::{print_util, TreeNode};
/* Driver Code */
fn main() {
/* Initialize binary tree */
// Initialize nodes
let n1 = TreeNode::new(1);
let n2 = TreeNode::new(2);
let n3 = TreeNode::new(3);
let n4 = TreeNode::new(4);
let n5 = TreeNode::new(5);
// Build references (pointers) between nodes
n1.borrow_mut().left = Some(Rc::clone(&n2));
n1.borrow_mut().right = Some(Rc::clone(&n3));
n2.borrow_mut().left = Some(Rc::clone(&n4));
n2.borrow_mut().right = Some(Rc::clone(&n5));
println!("\nInitialize binary tree\n");
print_util::print_tree(&n1);
// Insert node and delete node
let p = TreeNode::new(0);
// Delete node
p.borrow_mut().left = Some(Rc::clone(&n2));
n1.borrow_mut().left = Some(Rc::clone(&p));
println!("\nAfter inserting node P\n");
print_util::print_tree(&n1);
// Remove node P
drop(p);
n1.borrow_mut().left = Some(Rc::clone(&n2));
println!("\nAfter removing node P\n");
print_util::print_tree(&n1);
}
@@ -0,0 +1,45 @@
/*
* File: binary_tree_bfs.rs
* Created Time: 2023-04-07
* Author: xBLACKICEx (xBLACKICE@outlook.com)
*/
use hello_algo_rust::include::{print_util, vec_to_tree, TreeNode};
use hello_algo_rust::op_vec;
use std::collections::VecDeque;
use std::{cell::RefCell, rc::Rc};
/* Level-order traversal */
fn level_order(root: &Rc<RefCell<TreeNode>>) -> Vec<i32> {
// Initialize queue, add root node
let mut que = VecDeque::new();
que.push_back(root.clone());
// Initialize a list to save the traversal sequence
let mut vec = Vec::new();
while let Some(node) = que.pop_front() {
// Dequeue
vec.push(node.borrow().val); // Save node value
if let Some(left) = node.borrow().left.as_ref() {
que.push_back(left.clone()); // Left child node enqueue
}
if let Some(right) = node.borrow().right.as_ref() {
que.push_back(right.clone()); // Right child node enqueue
};
}
vec
}
/* Driver Code */
fn main() {
/* Initialize binary tree */
// Here we use a function to generate a binary tree directly from an array
let root = vec_to_tree(op_vec![1, 2, 3, 4, 5, 6, 7]).unwrap();
println!("Initialize binary tree\n");
print_util::print_tree(&root);
/* Level-order traversal */
let vec = level_order(&root);
print!("\nLevel-order traversal node sequence = {:?}", vec);
}
@@ -0,0 +1,87 @@
/*
* File: binary_tree_dfs.rs
* Created Time: 2023-04-06
* Author: xBLACKICEx (xBLACKICE@outlook.com)
*/
use hello_algo_rust::include::{print_util, vec_to_tree, TreeNode};
use hello_algo_rust::op_vec;
use std::cell::RefCell;
use std::rc::Rc;
/* Preorder traversal */
fn pre_order(root: Option<&Rc<RefCell<TreeNode>>>) -> Vec<i32> {
let mut result = vec![];
fn dfs(root: Option<&Rc<RefCell<TreeNode>>>, res: &mut Vec<i32>) {
if let Some(node) = root {
// Visit priority: root node -> left subtree -> right subtree
let node = node.borrow();
res.push(node.val);
dfs(node.left.as_ref(), res);
dfs(node.right.as_ref(), res);
}
}
dfs(root, &mut result);
result
}
/* Inorder traversal */
fn in_order(root: Option<&Rc<RefCell<TreeNode>>>) -> Vec<i32> {
let mut result = vec![];
fn dfs(root: Option<&Rc<RefCell<TreeNode>>>, res: &mut Vec<i32>) {
if let Some(node) = root {
// Visit priority: left subtree -> root node -> right subtree
let node = node.borrow();
dfs(node.left.as_ref(), res);
res.push(node.val);
dfs(node.right.as_ref(), res);
}
}
dfs(root, &mut result);
result
}
/* Postorder traversal */
fn post_order(root: Option<&Rc<RefCell<TreeNode>>>) -> Vec<i32> {
let mut result = vec![];
fn dfs(root: Option<&Rc<RefCell<TreeNode>>>, res: &mut Vec<i32>) {
if let Some(node) = root {
// Visit priority: left subtree -> right subtree -> root node
let node = node.borrow();
dfs(node.left.as_ref(), res);
dfs(node.right.as_ref(), res);
res.push(node.val);
}
}
dfs(root, &mut result);
result
}
/* Driver Code */
fn main() {
/* Initialize binary tree */
// Here we use a function to generate a binary tree directly from an array
let root = vec_to_tree(op_vec![1, 2, 3, 4, 5, 6, 7]);
println!("Initialize binary tree\n");
print_util::print_tree(root.as_ref().unwrap());
/* Preorder traversal */
let vec = pre_order(root.as_ref());
println!("\nPre-order traversal node sequence = {:?}", vec);
/* Inorder traversal */
let vec = in_order(root.as_ref());
println!("\nIn-order traversal node sequence = {:?}", vec);
/* Postorder traversal */
let vec = post_order(root.as_ref());
print!("\nPost-order traversal node sequence = {:?}", vec);
}