mirror of
https://github.com/krahets/hello-algo.git
synced 2026-04-15 02:40:58 +08:00
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:
@@ -12,7 +12,7 @@ from modules import TreeNode, list_to_tree, print_tree
|
||||
|
||||
|
||||
class ArrayBinaryTree:
|
||||
"""Array-based binary tree class"""
|
||||
"""Binary tree class represented by array"""
|
||||
|
||||
def __init__(self, arr: list[int | None]):
|
||||
"""Constructor"""
|
||||
@@ -23,28 +23,28 @@ class ArrayBinaryTree:
|
||||
return len(self._tree)
|
||||
|
||||
def val(self, i: int) -> int | None:
|
||||
"""Get the value of the node at index i"""
|
||||
# If the index is out of bounds, return None, representing a vacancy
|
||||
"""Get value of node at index i"""
|
||||
# If index is out of bounds, return None, representing empty position
|
||||
if i < 0 or i >= self.size():
|
||||
return None
|
||||
return self._tree[i]
|
||||
|
||||
def left(self, i: int) -> int | None:
|
||||
"""Get the index of the left child of the node at index i"""
|
||||
"""Get index of left child node of node at index i"""
|
||||
return 2 * i + 1
|
||||
|
||||
def right(self, i: int) -> int | None:
|
||||
"""Get the index of the right child of the node at index i"""
|
||||
"""Get index of right child node of node at index i"""
|
||||
return 2 * i + 2
|
||||
|
||||
def parent(self, i: int) -> int | None:
|
||||
"""Get the index of the parent of the node at index i"""
|
||||
"""Get index of parent node of node at index i"""
|
||||
return (i - 1) // 2
|
||||
|
||||
def level_order(self) -> list[int]:
|
||||
"""Level-order traversal"""
|
||||
self.res = []
|
||||
# Traverse array
|
||||
# Traverse array directly
|
||||
for i in range(self.size()):
|
||||
if self.val(i) is not None:
|
||||
self.res.append(self.val(i))
|
||||
@@ -54,32 +54,32 @@ class ArrayBinaryTree:
|
||||
"""Depth-first traversal"""
|
||||
if self.val(i) is None:
|
||||
return
|
||||
# Pre-order traversal
|
||||
# Preorder traversal
|
||||
if order == "pre":
|
||||
self.res.append(self.val(i))
|
||||
self.dfs(self.left(i), order)
|
||||
# In-order traversal
|
||||
# Inorder traversal
|
||||
if order == "in":
|
||||
self.res.append(self.val(i))
|
||||
self.dfs(self.right(i), order)
|
||||
# Post-order traversal
|
||||
# Postorder traversal
|
||||
if order == "post":
|
||||
self.res.append(self.val(i))
|
||||
|
||||
def pre_order(self) -> list[int]:
|
||||
"""Pre-order traversal"""
|
||||
"""Preorder traversal"""
|
||||
self.res = []
|
||||
self.dfs(0, order="pre")
|
||||
return self.res
|
||||
|
||||
def in_order(self) -> list[int]:
|
||||
"""In-order traversal"""
|
||||
"""Inorder traversal"""
|
||||
self.res = []
|
||||
self.dfs(0, order="in")
|
||||
return self.res
|
||||
|
||||
def post_order(self) -> list[int]:
|
||||
"""Post-order traversal"""
|
||||
"""Postorder traversal"""
|
||||
self.res = []
|
||||
self.dfs(0, order="post")
|
||||
return self.res
|
||||
@@ -88,32 +88,32 @@ class ArrayBinaryTree:
|
||||
"""Driver Code"""
|
||||
if __name__ == "__main__":
|
||||
# Initialize binary tree
|
||||
# Use a specific function to convert an array into a binary tree
|
||||
# Here we use a function to generate a binary tree directly from an array
|
||||
arr = [1, 2, 3, 4, None, 6, 7, 8, 9, None, None, 12, None, None, 15]
|
||||
root = list_to_tree(arr)
|
||||
print("\nInitialize binary tree\n")
|
||||
print("Array representation of the binary tree:")
|
||||
print("Array representation of binary tree:")
|
||||
print(arr)
|
||||
print("Linked list representation of the binary tree:")
|
||||
print("Linked list representation of binary tree:")
|
||||
print_tree(root)
|
||||
|
||||
# Array-based binary tree class
|
||||
# Binary tree class represented by array
|
||||
abt = ArrayBinaryTree(arr)
|
||||
|
||||
# Access node
|
||||
# Access nodes
|
||||
i = 1
|
||||
l, r, p = abt.left(i), abt.right(i), abt.parent(i)
|
||||
print(f"\nCurrent node index is {i}, value is {abt.val(i)}")
|
||||
print(f"Its left child node index is {l}, value is {abt.val(l)}")
|
||||
print(f"Its right child node index is {r}, value is {abt.val(r)}")
|
||||
print(f"Its parent node index is {p}, value is {abt.val(p)}")
|
||||
print(f"\nCurrent node's index is {i}, value is {abt.val(i)}")
|
||||
print(f"Its left child node's index is {l}, value is {abt.val(l)}")
|
||||
print(f"Its right child node's index is {r}, value is {abt.val(r)}")
|
||||
print(f"Its parent node's index is {p}, value is {abt.val(p)}")
|
||||
|
||||
# Traverse tree
|
||||
res = abt.level_order()
|
||||
print("\nLevel-order traversal is:", res)
|
||||
res = abt.pre_order()
|
||||
print("Pre-order traversal is:", res)
|
||||
print("Preorder traversal is:", res)
|
||||
res = abt.in_order()
|
||||
print("In-order traversal is:", res)
|
||||
print("Inorder traversal is:", res)
|
||||
res = abt.post_order()
|
||||
print("Post-order traversal is:", res)
|
||||
print("Postorder traversal is:", res)
|
||||
|
||||
@@ -46,31 +46,31 @@ class AVLTree:
|
||||
"""Right rotation operation"""
|
||||
child = node.left
|
||||
grand_child = child.right
|
||||
# Rotate node to the right around child
|
||||
# Using child as pivot, rotate node to the right
|
||||
child.right = node
|
||||
node.left = grand_child
|
||||
# Update node height
|
||||
self.update_height(node)
|
||||
self.update_height(child)
|
||||
# Return the root of the subtree after rotation
|
||||
# Return root node of subtree after rotation
|
||||
return child
|
||||
|
||||
def left_rotate(self, node: TreeNode | None) -> TreeNode | None:
|
||||
"""Left rotation operation"""
|
||||
child = node.right
|
||||
grand_child = child.left
|
||||
# Rotate node to the left around child
|
||||
# Using child as pivot, rotate node to the left
|
||||
child.left = node
|
||||
node.right = grand_child
|
||||
# Update node height
|
||||
self.update_height(node)
|
||||
self.update_height(child)
|
||||
# Return the root of the subtree after rotation
|
||||
# Return root node of subtree after rotation
|
||||
return child
|
||||
|
||||
def rotate(self, node: TreeNode | None) -> TreeNode | None:
|
||||
"""Perform rotation operation to restore balance to the subtree"""
|
||||
# Get the balance factor of node
|
||||
"""Perform rotation operation to restore balance to this subtree"""
|
||||
# Get balance factor of node
|
||||
balance_factor = self.balance_factor(node)
|
||||
# Left-leaning tree
|
||||
if balance_factor > 1:
|
||||
@@ -90,7 +90,7 @@ class AVLTree:
|
||||
# First right rotation then left rotation
|
||||
node.right = self.right_rotate(node.right)
|
||||
return self.left_rotate(node)
|
||||
# Balanced tree, no rotation needed, return
|
||||
# Balanced tree, no rotation needed, return directly
|
||||
return node
|
||||
|
||||
def insert(self, val):
|
||||
@@ -107,22 +107,22 @@ class AVLTree:
|
||||
elif val > node.val:
|
||||
node.right = self.insert_helper(node.right, val)
|
||||
else:
|
||||
# Do not insert duplicate nodes, return
|
||||
# Duplicate node not inserted, return directly
|
||||
return node
|
||||
# Update node height
|
||||
self.update_height(node)
|
||||
# 2. Perform rotation operation to restore balance to the subtree
|
||||
# 2. Perform rotation operation to restore balance to this subtree
|
||||
return self.rotate(node)
|
||||
|
||||
def remove(self, val: int):
|
||||
"""Remove node"""
|
||||
"""Delete node"""
|
||||
self._root = self.remove_helper(self._root, val)
|
||||
|
||||
def remove_helper(self, node: TreeNode | None, val: int) -> TreeNode | None:
|
||||
"""Recursively remove node (helper method)"""
|
||||
"""Recursively delete node (helper method)"""
|
||||
if node is None:
|
||||
return None
|
||||
# 1. Find and remove the node
|
||||
# 1. Find node and delete
|
||||
if val < node.val:
|
||||
node.left = self.remove_helper(node.left, val)
|
||||
elif val > node.val:
|
||||
@@ -130,14 +130,14 @@ class AVLTree:
|
||||
else:
|
||||
if node.left is None or node.right is None:
|
||||
child = node.left or node.right
|
||||
# Number of child nodes = 0, remove node and return
|
||||
# Number of child nodes = 0, delete node directly and return
|
||||
if child is None:
|
||||
return None
|
||||
# Number of child nodes = 1, remove node
|
||||
# Number of child nodes = 1, delete node directly
|
||||
else:
|
||||
node = child
|
||||
else:
|
||||
# Number of child nodes = 2, remove the next node in in-order traversal and replace the current node with it
|
||||
# Number of child nodes = 2, delete the next node in inorder traversal and replace current node with it
|
||||
temp = node.right
|
||||
while temp.left is not None:
|
||||
temp = temp.left
|
||||
@@ -145,13 +145,13 @@ class AVLTree:
|
||||
node.val = temp.val
|
||||
# Update node height
|
||||
self.update_height(node)
|
||||
# 2. Perform rotation operation to restore balance to the subtree
|
||||
# 2. Perform rotation operation to restore balance to this subtree
|
||||
return self.rotate(node)
|
||||
|
||||
def search(self, val: int) -> TreeNode | None:
|
||||
"""Search node"""
|
||||
cur = self._root
|
||||
# Loop find, break after passing leaf nodes
|
||||
# Loop search, exit after passing leaf node
|
||||
while cur is not None:
|
||||
# Target node is in cur's right subtree
|
||||
if cur.val < val:
|
||||
@@ -159,7 +159,7 @@ class AVLTree:
|
||||
# Target node is in cur's left subtree
|
||||
elif cur.val > val:
|
||||
cur = cur.left
|
||||
# Found target node, break loop
|
||||
# Found target node, exit loop
|
||||
else:
|
||||
break
|
||||
# Return target node
|
||||
@@ -171,30 +171,30 @@ if __name__ == "__main__":
|
||||
|
||||
def test_insert(tree: AVLTree, val: int):
|
||||
tree.insert(val)
|
||||
print("\nInsert node {} after, AVL tree is".format(val))
|
||||
print("\nAfter inserting node {}, AVL tree is".format(val))
|
||||
print_tree(tree.get_root())
|
||||
|
||||
def test_remove(tree: AVLTree, val: int):
|
||||
tree.remove(val)
|
||||
print("\nRemove node {} after, AVL tree is".format(val))
|
||||
print("\nAfter deleting node {}, AVL tree is".format(val))
|
||||
print_tree(tree.get_root())
|
||||
|
||||
# Initialize empty AVL tree
|
||||
avl_tree = AVLTree()
|
||||
|
||||
# Insert node
|
||||
# Notice how the AVL tree maintains balance after inserting nodes
|
||||
# Insert nodes
|
||||
# Please pay attention to how the AVL tree maintains balance after inserting nodes
|
||||
for val in [1, 2, 3, 4, 5, 8, 7, 9, 10, 6]:
|
||||
test_insert(avl_tree, val)
|
||||
|
||||
# Insert duplicate node
|
||||
test_insert(avl_tree, 7)
|
||||
|
||||
# Remove node
|
||||
# Notice how the AVL tree maintains balance after removing nodes
|
||||
test_remove(avl_tree, 8) # Remove node with degree 0
|
||||
test_remove(avl_tree, 5) # Remove node with degree 1
|
||||
test_remove(avl_tree, 4) # Remove node with degree 2
|
||||
# Delete nodes
|
||||
# Please pay attention to how the AVL tree maintains balance after deleting nodes
|
||||
test_remove(avl_tree, 8) # Delete node with degree 0
|
||||
test_remove(avl_tree, 5) # Delete node with degree 1
|
||||
test_remove(avl_tree, 4) # Delete node with degree 2
|
||||
|
||||
result_node = avl_tree.search(7)
|
||||
print("\nFound node object is {}, node value = {}".format(result_node, result_node.val))
|
||||
|
||||
@@ -26,7 +26,7 @@ class BinarySearchTree:
|
||||
def search(self, num: int) -> TreeNode | None:
|
||||
"""Search node"""
|
||||
cur = self._root
|
||||
# Loop find, break after passing leaf nodes
|
||||
# Loop search, exit after passing leaf node
|
||||
while cur is not None:
|
||||
# Target node is in cur's right subtree
|
||||
if cur.val < num:
|
||||
@@ -34,7 +34,7 @@ class BinarySearchTree:
|
||||
# Target node is in cur's left subtree
|
||||
elif cur.val > num:
|
||||
cur = cur.left
|
||||
# Found target node, break loop
|
||||
# Found target node, exit loop
|
||||
else:
|
||||
break
|
||||
return cur
|
||||
@@ -45,10 +45,10 @@ class BinarySearchTree:
|
||||
if self._root is None:
|
||||
self._root = TreeNode(num)
|
||||
return
|
||||
# Loop find, break after passing leaf nodes
|
||||
# Loop search, exit after passing leaf node
|
||||
cur, pre = self._root, None
|
||||
while cur is not None:
|
||||
# Found duplicate node, thus return
|
||||
# Found duplicate node, return directly
|
||||
if cur.val == num:
|
||||
return
|
||||
pre = cur
|
||||
@@ -66,47 +66,47 @@ class BinarySearchTree:
|
||||
pre.left = node
|
||||
|
||||
def remove(self, num: int):
|
||||
"""Remove node"""
|
||||
# If tree is empty, return
|
||||
"""Delete node"""
|
||||
# If tree is empty, return directly
|
||||
if self._root is None:
|
||||
return
|
||||
# Loop find, break after passing leaf nodes
|
||||
# Loop search, exit after passing leaf node
|
||||
cur, pre = self._root, None
|
||||
while cur is not None:
|
||||
# Found node to be removed, break loop
|
||||
# Found node to delete, exit loop
|
||||
if cur.val == num:
|
||||
break
|
||||
pre = cur
|
||||
# Node to be removed is in cur's right subtree
|
||||
# Node to delete is in cur's right subtree
|
||||
if cur.val < num:
|
||||
cur = cur.right
|
||||
# Node to be removed is in cur's left subtree
|
||||
# Node to delete is in cur's left subtree
|
||||
else:
|
||||
cur = cur.left
|
||||
# If no node to be removed, return
|
||||
# If no node to delete, return directly
|
||||
if cur is None:
|
||||
return
|
||||
|
||||
# Number of child nodes = 0 or 1
|
||||
if cur.left is None or cur.right is None:
|
||||
# When the number of child nodes = 0/1, child = null/that child node
|
||||
# When number of child nodes = 0 / 1, child = null / that child node
|
||||
child = cur.left or cur.right
|
||||
# Remove node cur
|
||||
# Delete node cur
|
||||
if cur != self._root:
|
||||
if pre.left == cur:
|
||||
pre.left = child
|
||||
else:
|
||||
pre.right = child
|
||||
else:
|
||||
# If the removed node is the root, reassign the root
|
||||
# If deleted node is root node, reassign root node
|
||||
self._root = child
|
||||
# Number of child nodes = 2
|
||||
else:
|
||||
# Get the next node in in-order traversal of cur
|
||||
# Get next node of cur in inorder traversal
|
||||
tmp: TreeNode = cur.right
|
||||
while tmp.left is not None:
|
||||
tmp = tmp.left
|
||||
# Recursively remove node tmp
|
||||
# Recursively delete node tmp
|
||||
self.remove(tmp.val)
|
||||
# Replace cur with tmp
|
||||
cur.val = tmp.val
|
||||
@@ -117,7 +117,7 @@ if __name__ == "__main__":
|
||||
# Initialize binary search tree
|
||||
bst = BinarySearchTree()
|
||||
nums = [8, 4, 12, 2, 6, 10, 14, 1, 3, 5, 7, 9, 11, 13, 15]
|
||||
# Note that different insertion orders can result in various tree structures. This particular sequence creates a perfect binary tree
|
||||
# Please note that different insertion orders will generate different binary trees, this sequence can generate a perfect binary tree
|
||||
for num in nums:
|
||||
bst.insert(num)
|
||||
print("\nInitialized binary tree is\n")
|
||||
@@ -129,18 +129,18 @@ if __name__ == "__main__":
|
||||
|
||||
# Insert node
|
||||
bst.insert(16)
|
||||
print("\nAfter inserting node 16, the binary tree is\n")
|
||||
print("\nAfter inserting node 16, binary tree is\n")
|
||||
print_tree(bst.get_root())
|
||||
|
||||
# Remove node
|
||||
# Delete node
|
||||
bst.remove(1)
|
||||
print("\nAfter removing node 1, the binary tree is\n")
|
||||
print("\nAfter deleting node 1, binary tree is\n")
|
||||
print_tree(bst.get_root())
|
||||
|
||||
bst.remove(2)
|
||||
print("\nAfter removing node 2, the binary tree is\n")
|
||||
print("\nAfter deleting node 2, binary tree is\n")
|
||||
print_tree(bst.get_root())
|
||||
|
||||
bst.remove(4)
|
||||
print("\nAfter removing node 4, the binary tree is\n")
|
||||
print("\nAfter deleting node 4, binary tree is\n")
|
||||
print_tree(bst.get_root())
|
||||
|
||||
@@ -14,13 +14,13 @@ from modules import TreeNode, print_tree
|
||||
"""Driver Code"""
|
||||
if __name__ == "__main__":
|
||||
# Initialize binary tree
|
||||
# Initialize node
|
||||
# Initialize nodes
|
||||
n1 = TreeNode(val=1)
|
||||
n2 = TreeNode(val=2)
|
||||
n3 = TreeNode(val=3)
|
||||
n4 = TreeNode(val=4)
|
||||
n5 = TreeNode(val=5)
|
||||
# Construct node references (pointers)
|
||||
# Build references (pointers) between nodes
|
||||
n1.left = n2
|
||||
n1.right = n3
|
||||
n2.left = n4
|
||||
@@ -28,14 +28,14 @@ if __name__ == "__main__":
|
||||
print("\nInitialize binary tree\n")
|
||||
print_tree(n1)
|
||||
|
||||
# Insert and remove nodes
|
||||
# Insert and delete nodes
|
||||
P = TreeNode(0)
|
||||
# Insert node P between n1 -> n2
|
||||
n1.left = P
|
||||
P.left = n2
|
||||
print("\nAfter inserting node P\n")
|
||||
print_tree(n1)
|
||||
# Remove node
|
||||
# Delete node
|
||||
n1.left = n2
|
||||
print("\nAfter removing node P\n")
|
||||
print("\nAfter deleting node P\n")
|
||||
print_tree(n1)
|
||||
|
||||
@@ -17,26 +17,26 @@ def level_order(root: TreeNode | None) -> list[int]:
|
||||
# Initialize queue, add root node
|
||||
queue: deque[TreeNode] = deque()
|
||||
queue.append(root)
|
||||
# Initialize a list to store the traversal sequence
|
||||
# Initialize a list to save the traversal sequence
|
||||
res = []
|
||||
while queue:
|
||||
node: TreeNode = queue.popleft() # Queue dequeues
|
||||
node: TreeNode = queue.popleft() # Dequeue
|
||||
res.append(node.val) # Save node value
|
||||
if node.left is not None:
|
||||
queue.append(node.left) # Left child node enqueues
|
||||
queue.append(node.left) # Left child node enqueue
|
||||
if node.right is not None:
|
||||
queue.append(node.right) # Right child node enqueues
|
||||
queue.append(node.right) # Right child node enqueue
|
||||
return res
|
||||
|
||||
|
||||
"""Driver Code"""
|
||||
if __name__ == "__main__":
|
||||
# Initialize binary tree
|
||||
# Use a specific function to convert an array into a binary tree
|
||||
# Here we use a function to generate a binary tree directly from an array
|
||||
root: TreeNode = list_to_tree(arr=[1, 2, 3, 4, 5, 6, 7])
|
||||
print("\nInitialize binary tree\n")
|
||||
print_tree(root)
|
||||
|
||||
# Level-order traversal
|
||||
res: list[int] = level_order(root)
|
||||
print("\nPrint sequence of nodes from level-order traversal = ", res)
|
||||
print("\nLevel-order traversal node print sequence = ", res)
|
||||
|
||||
@@ -12,7 +12,7 @@ from modules import TreeNode, list_to_tree, print_tree
|
||||
|
||||
|
||||
def pre_order(root: TreeNode | None):
|
||||
"""Pre-order traversal"""
|
||||
"""Preorder traversal"""
|
||||
if root is None:
|
||||
return
|
||||
# Visit priority: root node -> left subtree -> right subtree
|
||||
@@ -22,7 +22,7 @@ def pre_order(root: TreeNode | None):
|
||||
|
||||
|
||||
def in_order(root: TreeNode | None):
|
||||
"""In-order traversal"""
|
||||
"""Inorder traversal"""
|
||||
if root is None:
|
||||
return
|
||||
# Visit priority: left subtree -> root node -> right subtree
|
||||
@@ -32,7 +32,7 @@ def in_order(root: TreeNode | None):
|
||||
|
||||
|
||||
def post_order(root: TreeNode | None):
|
||||
"""Post-order traversal"""
|
||||
"""Postorder traversal"""
|
||||
if root is None:
|
||||
return
|
||||
# Visit priority: left subtree -> right subtree -> root node
|
||||
@@ -44,22 +44,22 @@ def post_order(root: TreeNode | None):
|
||||
"""Driver Code"""
|
||||
if __name__ == "__main__":
|
||||
# Initialize binary tree
|
||||
# Use a specific function to convert an array into a binary tree
|
||||
# Here we use a function to generate a binary tree directly from an array
|
||||
root = list_to_tree(arr=[1, 2, 3, 4, 5, 6, 7])
|
||||
print("\nInitialize binary tree\n")
|
||||
print_tree(root)
|
||||
|
||||
# Pre-order traversal
|
||||
# Preorder traversal
|
||||
res = []
|
||||
pre_order(root)
|
||||
print("\nPrint sequence of nodes from pre-order traversal = ", res)
|
||||
print("\nPreorder traversal node print sequence = ", res)
|
||||
|
||||
# In-order traversal
|
||||
# Inorder traversal
|
||||
res.clear()
|
||||
in_order(root)
|
||||
print("\nPrint sequence of nodes from in-order traversal = ", res)
|
||||
print("\nInorder traversal node print sequence = ", res)
|
||||
|
||||
# Post-order traversal
|
||||
# Postorder traversal
|
||||
res.clear()
|
||||
post_order(root)
|
||||
print("\nPrint sequence of nodes from post-order traversal = ", res)
|
||||
print("\nPostorder traversal node print sequence = ", res)
|
||||
|
||||
Reference in New Issue
Block a user