mirror of
https://github.com/krahets/hello-algo.git
synced 2026-04-05 11:41:22 +08:00
translation: Add Python and Java code for EN version (#1345)
* Add the intial translation of code of all the languages * test * revert * Remove * Add Python and Java code for EN version
This commit is contained in:
119
en/codes/python/chapter_tree/array_binary_tree.py
Normal file
119
en/codes/python/chapter_tree/array_binary_tree.py
Normal file
@@ -0,0 +1,119 @@
|
||||
"""
|
||||
File: array_binary_tree.py
|
||||
Created Time: 2023-07-19
|
||||
Author: krahets (krahets@163.com)
|
||||
"""
|
||||
|
||||
import sys
|
||||
from pathlib import Path
|
||||
|
||||
sys.path.append(str(Path(__file__).parent.parent))
|
||||
from modules import TreeNode, list_to_tree, print_tree
|
||||
|
||||
|
||||
class ArrayBinaryTree:
|
||||
"""Array-based binary tree class"""
|
||||
|
||||
def __init__(self, arr: list[int | None]):
|
||||
"""Constructor"""
|
||||
self._tree = list(arr)
|
||||
|
||||
def size(self):
|
||||
"""List capacity"""
|
||||
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
|
||||
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"""
|
||||
return 2 * i + 1
|
||||
|
||||
def right(self, i: int) -> int | None:
|
||||
"""Get the index of the right child of the 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"""
|
||||
return (i - 1) // 2
|
||||
|
||||
def level_order(self) -> list[int]:
|
||||
"""Level-order traversal"""
|
||||
self.res = []
|
||||
# Traverse array
|
||||
for i in range(self.size()):
|
||||
if self.val(i) is not None:
|
||||
self.res.append(self.val(i))
|
||||
return self.res
|
||||
|
||||
def dfs(self, i: int, order: str):
|
||||
"""Depth-first traversal"""
|
||||
if self.val(i) is None:
|
||||
return
|
||||
# Pre-order traversal
|
||||
if order == "pre":
|
||||
self.res.append(self.val(i))
|
||||
self.dfs(self.left(i), order)
|
||||
# In-order traversal
|
||||
if order == "in":
|
||||
self.res.append(self.val(i))
|
||||
self.dfs(self.right(i), order)
|
||||
# Post-order traversal
|
||||
if order == "post":
|
||||
self.res.append(self.val(i))
|
||||
|
||||
def pre_order(self) -> list[int]:
|
||||
"""Pre-order traversal"""
|
||||
self.res = []
|
||||
self.dfs(0, order="pre")
|
||||
return self.res
|
||||
|
||||
def in_order(self) -> list[int]:
|
||||
"""In-order traversal"""
|
||||
self.res = []
|
||||
self.dfs(0, order="in")
|
||||
return self.res
|
||||
|
||||
def post_order(self) -> list[int]:
|
||||
"""Post-order traversal"""
|
||||
self.res = []
|
||||
self.dfs(0, order="post")
|
||||
return self.res
|
||||
|
||||
|
||||
"""Driver Code"""
|
||||
if __name__ == "__main__":
|
||||
# Initialize binary tree
|
||||
# Use a specific function to convert an array into a binary tree
|
||||
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(arr)
|
||||
print("Linked list representation of the binary tree:")
|
||||
print_tree(root)
|
||||
|
||||
# Array-based binary tree class
|
||||
abt = ArrayBinaryTree(arr)
|
||||
|
||||
# Access node
|
||||
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)}")
|
||||
|
||||
# Traverse tree
|
||||
res = abt.level_order()
|
||||
print("\nLevel-order traversal is:", res)
|
||||
res = abt.pre_order()
|
||||
print("Pre-order traversal is:", res)
|
||||
res = abt.in_order()
|
||||
print("In-order traversal is:", res)
|
||||
res = abt.post_order()
|
||||
print("Post-order traversal is:", res)
|
||||
200
en/codes/python/chapter_tree/avl_tree.py
Normal file
200
en/codes/python/chapter_tree/avl_tree.py
Normal file
@@ -0,0 +1,200 @@
|
||||
"""
|
||||
File: avl_tree.py
|
||||
Created Time: 2022-12-20
|
||||
Author: a16su (lpluls001@gmail.com)
|
||||
"""
|
||||
|
||||
import sys
|
||||
from pathlib import Path
|
||||
|
||||
sys.path.append(str(Path(__file__).parent.parent))
|
||||
from modules import TreeNode, print_tree
|
||||
|
||||
|
||||
class AVLTree:
|
||||
"""AVL tree"""
|
||||
|
||||
def __init__(self):
|
||||
"""Constructor"""
|
||||
self._root = None
|
||||
|
||||
def get_root(self) -> TreeNode | None:
|
||||
"""Get binary tree root node"""
|
||||
return self._root
|
||||
|
||||
def height(self, node: TreeNode | None) -> int:
|
||||
"""Get node height"""
|
||||
# Empty node height is -1, leaf node height is 0
|
||||
if node is not None:
|
||||
return node.height
|
||||
return -1
|
||||
|
||||
def update_height(self, node: TreeNode | None):
|
||||
"""Update node height"""
|
||||
# Node height equals the height of the tallest subtree + 1
|
||||
node.height = max([self.height(node.left), self.height(node.right)]) + 1
|
||||
|
||||
def balance_factor(self, node: TreeNode | None) -> int:
|
||||
"""Get balance factor"""
|
||||
# Empty node balance factor is 0
|
||||
if node is None:
|
||||
return 0
|
||||
# Node balance factor = left subtree height - right subtree height
|
||||
return self.height(node.left) - self.height(node.right)
|
||||
|
||||
def right_rotate(self, node: TreeNode | None) -> TreeNode | None:
|
||||
"""Right rotation operation"""
|
||||
child = node.left
|
||||
grand_child = child.right
|
||||
# Rotate node to the right around child
|
||||
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 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
|
||||
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 child
|
||||
|
||||
def rotate(self, node: TreeNode | None) -> TreeNode | None:
|
||||
"""Perform rotation operation to restore balance to the subtree"""
|
||||
# Get the balance factor of node
|
||||
balance_factor = self.balance_factor(node)
|
||||
# Left-leaning tree
|
||||
if balance_factor > 1:
|
||||
if self.balance_factor(node.left) >= 0:
|
||||
# Right rotation
|
||||
return self.right_rotate(node)
|
||||
else:
|
||||
# First left rotation then right rotation
|
||||
node.left = self.left_rotate(node.left)
|
||||
return self.right_rotate(node)
|
||||
# Right-leaning tree
|
||||
elif balance_factor < -1:
|
||||
if self.balance_factor(node.right) <= 0:
|
||||
# Left rotation
|
||||
return self.left_rotate(node)
|
||||
else:
|
||||
# First right rotation then left rotation
|
||||
node.right = self.right_rotate(node.right)
|
||||
return self.left_rotate(node)
|
||||
# Balanced tree, no rotation needed, return
|
||||
return node
|
||||
|
||||
def insert(self, val):
|
||||
"""Insert node"""
|
||||
self._root = self.insert_helper(self._root, val)
|
||||
|
||||
def insert_helper(self, node: TreeNode | None, val: int) -> TreeNode:
|
||||
"""Recursively insert node (helper method)"""
|
||||
if node is None:
|
||||
return TreeNode(val)
|
||||
# 1. Find insertion position and insert node
|
||||
if val < node.val:
|
||||
node.left = self.insert_helper(node.left, val)
|
||||
elif val > node.val:
|
||||
node.right = self.insert_helper(node.right, val)
|
||||
else:
|
||||
# Do not insert duplicate nodes, return
|
||||
return node
|
||||
# Update node height
|
||||
self.update_height(node)
|
||||
# 2. Perform rotation operation to restore balance to the subtree
|
||||
return self.rotate(node)
|
||||
|
||||
def remove(self, val: int):
|
||||
"""Remove 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)"""
|
||||
if node is None:
|
||||
return None
|
||||
# 1. Find and remove the node
|
||||
if val < node.val:
|
||||
node.left = self.remove_helper(node.left, val)
|
||||
elif val > node.val:
|
||||
node.right = self.remove_helper(node.right, val)
|
||||
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
|
||||
if child is None:
|
||||
return None
|
||||
# Number of child nodes = 1, remove node
|
||||
else:
|
||||
node = child
|
||||
else:
|
||||
# Number of child nodes = 2, remove the next node in in-order traversal and replace the current node with it
|
||||
temp = node.right
|
||||
while temp.left is not None:
|
||||
temp = temp.left
|
||||
node.right = self.remove_helper(node.right, temp.val)
|
||||
node.val = temp.val
|
||||
# Update node height
|
||||
self.update_height(node)
|
||||
# 2. Perform rotation operation to restore balance to the subtree
|
||||
return self.rotate(node)
|
||||
|
||||
def search(self, val: int) -> TreeNode | None:
|
||||
"""Search node"""
|
||||
cur = self._root
|
||||
# Loop find, break after passing leaf nodes
|
||||
while cur is not None:
|
||||
# Target node is in cur's right subtree
|
||||
if cur.val < val:
|
||||
cur = cur.right
|
||||
# Target node is in cur's left subtree
|
||||
elif cur.val > val:
|
||||
cur = cur.left
|
||||
# Found target node, break loop
|
||||
else:
|
||||
break
|
||||
# Return target node
|
||||
return cur
|
||||
|
||||
|
||||
"""Driver Code"""
|
||||
if __name__ == "__main__":
|
||||
|
||||
def test_insert(tree: AVLTree, val: int):
|
||||
tree.insert(val)
|
||||
print("\nInsert node {} after, 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_tree(tree.get_root())
|
||||
|
||||
# Initialize empty AVL tree
|
||||
avl_tree = AVLTree()
|
||||
|
||||
# Insert node
|
||||
# Notice 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
|
||||
|
||||
result_node = avl_tree.search(7)
|
||||
print("\nFound node object is {}, node value = {}".format(result_node, result_node.val))
|
||||
146
en/codes/python/chapter_tree/binary_search_tree.py
Normal file
146
en/codes/python/chapter_tree/binary_search_tree.py
Normal file
@@ -0,0 +1,146 @@
|
||||
"""
|
||||
File: binary_search_tree.py
|
||||
Created Time: 2022-12-20
|
||||
Author: a16su (lpluls001@gmail.com)
|
||||
"""
|
||||
|
||||
import sys
|
||||
from pathlib import Path
|
||||
|
||||
sys.path.append(str(Path(__file__).parent.parent))
|
||||
from modules import TreeNode, print_tree
|
||||
|
||||
|
||||
class BinarySearchTree:
|
||||
"""Binary search tree"""
|
||||
|
||||
def __init__(self):
|
||||
"""Constructor"""
|
||||
# Initialize empty tree
|
||||
self._root = None
|
||||
|
||||
def get_root(self) -> TreeNode | None:
|
||||
"""Get binary tree root node"""
|
||||
return self._root
|
||||
|
||||
def search(self, num: int) -> TreeNode | None:
|
||||
"""Search node"""
|
||||
cur = self._root
|
||||
# Loop find, break after passing leaf nodes
|
||||
while cur is not None:
|
||||
# Target node is in cur's right subtree
|
||||
if cur.val < num:
|
||||
cur = cur.right
|
||||
# Target node is in cur's left subtree
|
||||
elif cur.val > num:
|
||||
cur = cur.left
|
||||
# Found target node, break loop
|
||||
else:
|
||||
break
|
||||
return cur
|
||||
|
||||
def insert(self, num: int):
|
||||
"""Insert node"""
|
||||
# If tree is empty, initialize root node
|
||||
if self._root is None:
|
||||
self._root = TreeNode(num)
|
||||
return
|
||||
# Loop find, break after passing leaf nodes
|
||||
cur, pre = self._root, None
|
||||
while cur is not None:
|
||||
# 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
|
||||
node = TreeNode(num)
|
||||
if pre.val < num:
|
||||
pre.right = node
|
||||
else:
|
||||
pre.left = node
|
||||
|
||||
def remove(self, num: int):
|
||||
"""Remove node"""
|
||||
# If tree is empty, return
|
||||
if self._root is None:
|
||||
return
|
||||
# Loop find, break after passing leaf nodes
|
||||
cur, pre = self._root, None
|
||||
while cur is not None:
|
||||
# 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 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
|
||||
child = cur.left or cur.right
|
||||
# Remove 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
|
||||
self._root = child
|
||||
# Number of child nodes = 2
|
||||
else:
|
||||
# Get the next node in in-order traversal of cur
|
||||
tmp: TreeNode = cur.right
|
||||
while tmp.left is not None:
|
||||
tmp = tmp.left
|
||||
# Recursively remove node tmp
|
||||
self.remove(tmp.val)
|
||||
# Replace cur with tmp
|
||||
cur.val = tmp.val
|
||||
|
||||
|
||||
"""Driver Code"""
|
||||
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
|
||||
for num in nums:
|
||||
bst.insert(num)
|
||||
print("\nInitialized binary tree is\n")
|
||||
print_tree(bst.get_root())
|
||||
|
||||
# Search node
|
||||
node = bst.search(7)
|
||||
print("\nFound node object is: {}, node value = {}".format(node, node.val))
|
||||
|
||||
# Insert node
|
||||
bst.insert(16)
|
||||
print("\nAfter inserting node 16, the binary tree is\n")
|
||||
print_tree(bst.get_root())
|
||||
|
||||
# Remove node
|
||||
bst.remove(1)
|
||||
print("\nAfter removing node 1, the binary tree is\n")
|
||||
print_tree(bst.get_root())
|
||||
|
||||
bst.remove(2)
|
||||
print("\nAfter removing node 2, the binary tree is\n")
|
||||
print_tree(bst.get_root())
|
||||
|
||||
bst.remove(4)
|
||||
print("\nAfter removing node 4, the binary tree is\n")
|
||||
print_tree(bst.get_root())
|
||||
41
en/codes/python/chapter_tree/binary_tree.py
Normal file
41
en/codes/python/chapter_tree/binary_tree.py
Normal file
@@ -0,0 +1,41 @@
|
||||
"""
|
||||
File: binary_tree.py
|
||||
Created Time: 2022-12-20
|
||||
Author: a16su (lpluls001@gmail.com)
|
||||
"""
|
||||
|
||||
import sys
|
||||
from pathlib import Path
|
||||
|
||||
sys.path.append(str(Path(__file__).parent.parent))
|
||||
from modules import TreeNode, print_tree
|
||||
|
||||
|
||||
"""Driver Code"""
|
||||
if __name__ == "__main__":
|
||||
# Initialize binary tree
|
||||
# Initialize node
|
||||
n1 = TreeNode(val=1)
|
||||
n2 = TreeNode(val=2)
|
||||
n3 = TreeNode(val=3)
|
||||
n4 = TreeNode(val=4)
|
||||
n5 = TreeNode(val=5)
|
||||
# Construct node references (pointers)
|
||||
n1.left = n2
|
||||
n1.right = n3
|
||||
n2.left = n4
|
||||
n2.right = n5
|
||||
print("\nInitialize binary tree\n")
|
||||
print_tree(n1)
|
||||
|
||||
# Insert and remove 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
|
||||
n1.left = n2
|
||||
print("\nAfter removing node P\n")
|
||||
print_tree(n1)
|
||||
42
en/codes/python/chapter_tree/binary_tree_bfs.py
Normal file
42
en/codes/python/chapter_tree/binary_tree_bfs.py
Normal file
@@ -0,0 +1,42 @@
|
||||
"""
|
||||
File: binary_tree_bfs.py
|
||||
Created Time: 2022-12-20
|
||||
Author: a16su (lpluls001@gmail.com)
|
||||
"""
|
||||
|
||||
import sys
|
||||
from pathlib import Path
|
||||
|
||||
sys.path.append(str(Path(__file__).parent.parent))
|
||||
from modules import TreeNode, list_to_tree, print_tree
|
||||
from collections import deque
|
||||
|
||||
|
||||
def level_order(root: TreeNode | None) -> list[int]:
|
||||
"""Level-order traversal"""
|
||||
# Initialize queue, add root node
|
||||
queue: deque[TreeNode] = deque()
|
||||
queue.append(root)
|
||||
# Initialize a list to store the traversal sequence
|
||||
res = []
|
||||
while queue:
|
||||
node: TreeNode = queue.popleft() # Queue dequeues
|
||||
res.append(node.val) # Save node value
|
||||
if node.left is not None:
|
||||
queue.append(node.left) # Left child node enqueues
|
||||
if node.right is not None:
|
||||
queue.append(node.right) # Right child node enqueues
|
||||
return res
|
||||
|
||||
|
||||
"""Driver Code"""
|
||||
if __name__ == "__main__":
|
||||
# Initialize binary tree
|
||||
# Use a specific function to convert an array into a binary tree
|
||||
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)
|
||||
65
en/codes/python/chapter_tree/binary_tree_dfs.py
Normal file
65
en/codes/python/chapter_tree/binary_tree_dfs.py
Normal file
@@ -0,0 +1,65 @@
|
||||
"""
|
||||
File: binary_tree_dfs.py
|
||||
Created Time: 2022-12-20
|
||||
Author: a16su (lpluls001@gmail.com)
|
||||
"""
|
||||
|
||||
import sys
|
||||
from pathlib import Path
|
||||
|
||||
sys.path.append(str(Path(__file__).parent.parent))
|
||||
from modules import TreeNode, list_to_tree, print_tree
|
||||
|
||||
|
||||
def pre_order(root: TreeNode | None):
|
||||
"""Pre-order traversal"""
|
||||
if root is None:
|
||||
return
|
||||
# Visit priority: root node -> left subtree -> right subtree
|
||||
res.append(root.val)
|
||||
pre_order(root=root.left)
|
||||
pre_order(root=root.right)
|
||||
|
||||
|
||||
def in_order(root: TreeNode | None):
|
||||
"""In-order traversal"""
|
||||
if root is None:
|
||||
return
|
||||
# Visit priority: left subtree -> root node -> right subtree
|
||||
in_order(root=root.left)
|
||||
res.append(root.val)
|
||||
in_order(root=root.right)
|
||||
|
||||
|
||||
def post_order(root: TreeNode | None):
|
||||
"""Post-order traversal"""
|
||||
if root is None:
|
||||
return
|
||||
# Visit priority: left subtree -> right subtree -> root node
|
||||
post_order(root=root.left)
|
||||
post_order(root=root.right)
|
||||
res.append(root.val)
|
||||
|
||||
|
||||
"""Driver Code"""
|
||||
if __name__ == "__main__":
|
||||
# Initialize binary tree
|
||||
# Use a specific function to convert an array into a binary tree
|
||||
root = list_to_tree(arr=[1, 2, 3, 4, 5, 6, 7])
|
||||
print("\nInitialize binary tree\n")
|
||||
print_tree(root)
|
||||
|
||||
# Pre-order traversal
|
||||
res = []
|
||||
pre_order(root)
|
||||
print("\nPrint sequence of nodes from pre-order traversal = ", res)
|
||||
|
||||
# In-order traversal
|
||||
res.clear()
|
||||
in_order(root)
|
||||
print("\nPrint sequence of nodes from in-order traversal = ", res)
|
||||
|
||||
# Post-order traversal
|
||||
res.clear()
|
||||
post_order(root)
|
||||
print("\nPrint sequence of nodes from post-order traversal = ", res)
|
||||
Reference in New Issue
Block a user