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:
Yudong Jin
2024-05-06 05:21:51 +08:00
committed by GitHub
parent b5e198db7d
commit 1c0f350ad6
174 changed files with 12349 additions and 0 deletions

View File

@@ -0,0 +1,136 @@
/**
* File: array_binary_tree.java
* Created Time: 2023-07-19
* Author: krahets (krahets@163.com)
*/
package chapter_tree;
import utils.*;
import java.util.*;
/* Array-based binary tree class */
class ArrayBinaryTree {
private List<Integer> tree;
/* Constructor */
public ArrayBinaryTree(List<Integer> arr) {
tree = new ArrayList<>(arr);
}
/* List capacity */
public int size() {
return tree.size();
}
/* Get the value of the node at index i */
public Integer val(int i) {
// If the index is out of bounds, return null, representing an empty spot
if (i < 0 || i >= size())
return null;
return tree.get(i);
}
/* Get the index of the left child of the node at index i */
public Integer left(int i) {
return 2 * i + 1;
}
/* Get the index of the right child of the node at index i */
public Integer right(int i) {
return 2 * i + 2;
}
/* Get the index of the parent of the node at index i */
public Integer parent(int i) {
return (i - 1) / 2;
}
/* Level-order traversal */
public List<Integer> levelOrder() {
List<Integer> res = new ArrayList<>();
// Traverse array
for (int i = 0; i < size(); i++) {
if (val(i) != null)
res.add(val(i));
}
return res;
}
/* Depth-first traversal */
private void dfs(Integer i, String order, List<Integer> res) {
// If it is an empty spot, return
if (val(i) == null)
return;
// Pre-order traversal
if ("pre".equals(order))
res.add(val(i));
dfs(left(i), order, res);
// In-order traversal
if ("in".equals(order))
res.add(val(i));
dfs(right(i), order, res);
// Post-order traversal
if ("post".equals(order))
res.add(val(i));
}
/* Pre-order traversal */
public List<Integer> preOrder() {
List<Integer> res = new ArrayList<>();
dfs(0, "pre", res);
return res;
}
/* In-order traversal */
public List<Integer> inOrder() {
List<Integer> res = new ArrayList<>();
dfs(0, "in", res);
return res;
}
/* Post-order traversal */
public List<Integer> postOrder() {
List<Integer> res = new ArrayList<>();
dfs(0, "post", res);
return res;
}
}
public class array_binary_tree {
public static void main(String[] args) {
// Initialize binary tree
// Use a specific function to convert an array into a binary tree
List<Integer> arr = Arrays.asList(1, 2, 3, 4, null, 6, 7, 8, 9, null, null, 12, null, null, 15);
TreeNode root = TreeNode.listToTree(arr);
System.out.println("\nInitialize binary tree\n");
System.out.println("Array representation of the binary tree:");
System.out.println(arr);
System.out.println("Linked list representation of the binary tree:");
PrintUtil.printTree(root);
// Array-based binary tree class
ArrayBinaryTree abt = new ArrayBinaryTree(arr);
// Access node
int i = 1;
Integer l = abt.left(i);
Integer r = abt.right(i);
Integer p = abt.parent(i);
System.out.println("\nThe current node's index is " + i + ", value = " + abt.val(i));
System.out.println("Its left child's index is " + l + ", value = " + (l == null ? "null" : abt.val(l)));
System.out.println("Its right child's index is " + r + ", value = " + (r == null ? "null" : abt.val(r)));
System.out.println("Its parent's index is " + p + ", value = " + (p == null ? "null" : abt.val(p)));
// Traverse tree
List<Integer> res = abt.levelOrder();
System.out.println("\nLevel-order traversal is:" + res);
res = abt.preOrder();
System.out.println("Pre-order traversal is:" + res);
res = abt.inOrder();
System.out.println("In-order traversal is:" + res);
res = abt.postOrder();
System.out.println("Post-order traversal is:" + res);
}
}

View File

@@ -0,0 +1,220 @@
/**
* File: avl_tree.java
* Created Time: 2022-12-10
* Author: krahets (krahets@163.com)
*/
package chapter_tree;
import utils.*;
/* AVL tree */
class AVLTree {
TreeNode root; // Root node
/* Get node height */
public int height(TreeNode node) {
// Empty node height is -1, leaf node height is 0
return node == null ? -1 : node.height;
}
/* Update node height */
private void updateHeight(TreeNode node) {
// Node height equals the height of the tallest subtree + 1
node.height = Math.max(height(node.left), height(node.right)) + 1;
}
/* Get balance factor */
public int balanceFactor(TreeNode node) {
// Empty node balance factor is 0
if (node == null)
return 0;
// Node balance factor = left subtree height - right subtree height
return height(node.left) - height(node.right);
}
/* Right rotation operation */
private 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 */
private 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 */
private 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;
}
/* Insert node */
public void insert(int val) {
root = insertHelper(root, val);
}
/* Recursively insert node (helper method) */
private TreeNode insertHelper(TreeNode node, int val) {
if (node == null)
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;
}
/* Remove node */
public void remove(int val) {
root = removeHelper(root, val);
}
/* Recursively remove node (helper method) */
private TreeNode removeHelper(TreeNode node, int val) {
if (node == null)
return null;
/* 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 == null || node.right == null) {
TreeNode child = node.left != null ? node.left : node.right;
// Number of child nodes = 0, remove node and return
if (child == null)
return null;
// 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
TreeNode temp = node.right;
while (temp.left != null) {
temp = temp.left;
}
node.right = removeHelper(node.right, temp.val);
node.val = temp.val;
}
}
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;
}
/* Search node */
public TreeNode search(int val) {
TreeNode cur = root;
// Loop find, break after passing leaf nodes
while (cur != null) {
// 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;
}
}
public class avl_tree {
static void testInsert(AVLTree tree, int val) {
tree.insert(val);
System.out.println("\nAfter inserting node " + val + ", the AVL tree is ");
PrintUtil.printTree(tree.root);
}
static void testRemove(AVLTree tree, int val) {
tree.remove(val);
System.out.println("\nAfter removing node " + val + ", the AVL tree is ");
PrintUtil.printTree(tree.root);
}
public static void main(String[] args) {
/* Initialize empty AVL tree */
AVLTree avlTree = new 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);
System.out.println("\nThe found node object is " + node + ", node value = " + node.val);
}
}

View File

@@ -0,0 +1,158 @@
/**
* File: binary_search_tree.java
* Created Time: 2022-11-25
* Author: krahets (krahets@163.com)
*/
package chapter_tree;
import utils.*;
/* Binary search tree */
class BinarySearchTree {
private TreeNode root;
/* Constructor */
public BinarySearchTree() {
// Initialize empty tree
root = null;
}
/* Get binary tree root node */
public TreeNode getRoot() {
return root;
}
/* Search node */
public TreeNode search(int num) {
TreeNode cur = root;
// Loop find, break after passing leaf nodes
while (cur != null) {
// 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 */
public void insert(int num) {
// If tree is empty, initialize root node
if (root == null) {
root = new TreeNode(num);
return;
}
TreeNode cur = root, pre = null;
// Loop find, break after passing leaf nodes
while (cur != null) {
// 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 */
public void remove(int num) {
// If tree is empty, return
if (root == null)
return;
TreeNode cur = root, pre = null;
// Loop find, break after passing leaf nodes
while (cur != null) {
// 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 == null)
return;
// Number of child nodes = 0 or 1
if (cur.left == null || cur.right == null) {
// When the number of child nodes = 0/1, child = null/that child node
TreeNode child = cur.left != null ? 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;
}
}
// Number of child nodes = 2
else {
// Get the next node in in-order traversal of cur
TreeNode tmp = cur.right;
while (tmp.left != null) {
tmp = tmp.left;
}
// Recursively remove node tmp
remove(tmp.val);
// Replace cur with tmp
cur.val = tmp.val;
}
}
}
public class binary_search_tree {
public static void main(String[] args) {
/* 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
int[] nums = { 8, 4, 12, 2, 6, 10, 14, 1, 3, 5, 7, 9, 11, 13, 15 };
for (int num : nums) {
bst.insert(num);
}
System.out.println("\nInitialized binary tree is\n");
PrintUtil.printTree(bst.getRoot());
/* Search node */
TreeNode node = bst.search(7);
System.out.println("\nThe found node object is " + node + ", node value = " + node.val);
/* Insert node */
bst.insert(16);
System.out.println("\nAfter inserting node 16, the binary tree is\n");
PrintUtil.printTree(bst.getRoot());
/* Remove node */
bst.remove(1);
System.out.println("\nAfter removing node 1, the binary tree is\n");
PrintUtil.printTree(bst.getRoot());
bst.remove(2);
System.out.println("\nAfter removing node 2, the binary tree is\n");
PrintUtil.printTree(bst.getRoot());
bst.remove(4);
System.out.println("\nAfter removing node 4, the binary tree is\n");
PrintUtil.printTree(bst.getRoot());
}
}

View File

@@ -0,0 +1,40 @@
/**
* File: binary_tree.java
* Created Time: 2022-11-25
* Author: krahets (krahets@163.com)
*/
package chapter_tree;
import utils.*;
public class binary_tree {
public static void main(String[] args) {
/* 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;
System.out.println("\nInitialize binary tree\n");
PrintUtil.printTree(n1);
/* Insert and remove nodes */
TreeNode P = new TreeNode(0);
// Insert node P between n1 -> n2
n1.left = P;
P.left = n2;
System.out.println("\nAfter inserting node P\n");
PrintUtil.printTree(n1);
// Remove node P
n1.left = n2;
System.out.println("\nAfter removing node P\n");
PrintUtil.printTree(n1);
}
}

View File

@@ -0,0 +1,42 @@
/**
* File: binary_tree_bfs.java
* Created Time: 2022-11-25
* Author: krahets (krahets@163.com)
*/
package chapter_tree;
import utils.*;
import java.util.*;
public class binary_tree_bfs {
/* Level-order traversal */
static List<Integer> levelOrder(TreeNode root) {
// Initialize queue, add root node
Queue<TreeNode> queue = new LinkedList<>();
queue.add(root);
// Initialize a list to store the traversal sequence
List<Integer> list = new ArrayList<>();
while (!queue.isEmpty()) {
TreeNode node = queue.poll(); // Queue dequeues
list.add(node.val); // Save node value
if (node.left != null)
queue.offer(node.left); // Left child node enqueues
if (node.right != null)
queue.offer(node.right); // Right child node enqueues
}
return list;
}
public static void main(String[] args) {
/* Initialize binary tree */
// Use a specific function to convert an array into a binary tree
TreeNode root = TreeNode.listToTree(Arrays.asList(1, 2, 3, 4, 5, 6, 7));
System.out.println("\nInitialize binary tree\n");
PrintUtil.printTree(root);
/* Level-order traversal */
List<Integer> list = levelOrder(root);
System.out.println("\nPrint sequence of nodes from level-order traversal = " + list);
}
}

View File

@@ -0,0 +1,68 @@
/**
* File: binary_tree_dfs.java
* Created Time: 2022-11-25
* Author: krahets (krahets@163.com)
*/
package chapter_tree;
import utils.*;
import java.util.*;
public class binary_tree_dfs {
// Initialize the list for storing traversal sequences
static ArrayList<Integer> list = new ArrayList<>();
/* Pre-order traversal */
static void preOrder(TreeNode root) {
if (root == null)
return;
// Visit priority: root node -> left subtree -> right subtree
list.add(root.val);
preOrder(root.left);
preOrder(root.right);
}
/* In-order traversal */
static void inOrder(TreeNode root) {
if (root == null)
return;
// Visit priority: left subtree -> root node -> right subtree
inOrder(root.left);
list.add(root.val);
inOrder(root.right);
}
/* Post-order traversal */
static void postOrder(TreeNode root) {
if (root == null)
return;
// Visit priority: left subtree -> right subtree -> root node
postOrder(root.left);
postOrder(root.right);
list.add(root.val);
}
public static void main(String[] args) {
/* Initialize binary tree */
// Use a specific function to convert an array into a binary tree
TreeNode root = TreeNode.listToTree(Arrays.asList(1, 2, 3, 4, 5, 6, 7));
System.out.println("\nInitialize binary tree\n");
PrintUtil.printTree(root);
/* Pre-order traversal */
list.clear();
preOrder(root);
System.out.println("\nPrint sequence of nodes from pre-order traversal = " + list);
/* In-order traversal */
list.clear();
inOrder(root);
System.out.println("\nPrint sequence of nodes from in-order traversal = " + list);
/* Post-order traversal */
list.clear();
postOrder(root);
System.out.println("\nPrint sequence of nodes from post-order traversal = " + list);
}
}