mirror of
https://github.com/krahets/hello-algo.git
synced 2026-11-10 16:00:36 +08:00
Retranslate the complete English edition from Simplified Chinese (#2010)
* Retranslate the complete English edition from Simplified Chinese * Polish three English explanations after reader-focused review
This commit is contained in:
@@ -12,39 +12,39 @@ from modules import TreeNode, list_to_tree, print_tree
|
||||
|
||||
|
||||
class ArrayBinaryTree:
|
||||
"""Binary tree class represented by array"""
|
||||
"""Binary tree class using an array representation"""
|
||||
|
||||
def __init__(self, arr: list[int | None]):
|
||||
"""Constructor"""
|
||||
self._tree = list(arr)
|
||||
|
||||
def size(self):
|
||||
"""List capacity"""
|
||||
"""Length of the backing list"""
|
||||
return len(self._tree)
|
||||
|
||||
def val(self, i: int) -> int | None:
|
||||
"""Get value of node at index i"""
|
||||
# If index is out of bounds, return None, representing empty position
|
||||
"""Get the value of the node at index i"""
|
||||
# If the index is out of bounds, return None to represent an empty position
|
||||
if i < 0 or i >= self.size():
|
||||
return None
|
||||
return self._tree[i]
|
||||
|
||||
def left(self, i: int) -> int | None:
|
||||
"""Get index of left child node of node at index i"""
|
||||
"""Get the left child index of the node at index i"""
|
||||
return 2 * i + 1
|
||||
|
||||
def right(self, i: int) -> int | None:
|
||||
"""Get index of right child node of node at index i"""
|
||||
"""Get the right child index of the node at index i"""
|
||||
return 2 * i + 2
|
||||
|
||||
def parent(self, i: int) -> int | None:
|
||||
"""Get index of parent node of node at index i"""
|
||||
"""Get the parent index of the node at index i"""
|
||||
return (i - 1) // 2
|
||||
|
||||
def level_order(self) -> list[int]:
|
||||
"""Level-order traversal"""
|
||||
self.res = []
|
||||
# Traverse array directly
|
||||
# Traverse the array directly
|
||||
for i in range(self.size()):
|
||||
if self.val(i) is not None:
|
||||
self.res.append(self.val(i))
|
||||
@@ -85,35 +85,35 @@ class ArrayBinaryTree:
|
||||
return self.res
|
||||
|
||||
|
||||
"""Driver Code"""
|
||||
"""Driver code"""
|
||||
if __name__ == "__main__":
|
||||
# Initialize binary tree
|
||||
# Here we use a function to generate a binary tree directly from an array
|
||||
# Initialize the binary tree
|
||||
# Use a helper function that builds 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 binary tree:")
|
||||
print("\nInitialize the binary tree\n")
|
||||
print("Array representation of the binary tree:")
|
||||
print(arr)
|
||||
print("Linked list representation of binary tree:")
|
||||
print("Linked representation of the binary tree:")
|
||||
print_tree(root)
|
||||
|
||||
# Binary tree class represented by array
|
||||
# Binary tree class using an array representation
|
||||
abt = ArrayBinaryTree(arr)
|
||||
|
||||
# Access nodes
|
||||
# Access a node
|
||||
i = 1
|
||||
l, r, p = abt.left(i), abt.right(i), abt.parent(i)
|
||||
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)}")
|
||||
print(f"\nCurrent node index: {i}, value: {abt.val(i)}")
|
||||
print(f"Left child index: {l}, value: {abt.val(l)}")
|
||||
print(f"Right child index: {r}, value: {abt.val(r)}")
|
||||
print(f"Parent index: {p}, value: {abt.val(p)}")
|
||||
|
||||
# Traverse tree
|
||||
# Traverse the tree
|
||||
res = abt.level_order()
|
||||
print("\nLevel-order traversal is:", res)
|
||||
print("\nLevel-order traversal:", res)
|
||||
res = abt.pre_order()
|
||||
print("Preorder traversal is:", res)
|
||||
print("Preorder traversal:", res)
|
||||
res = abt.in_order()
|
||||
print("Inorder traversal is:", res)
|
||||
print("Inorder traversal:", res)
|
||||
res = abt.post_order()
|
||||
print("Postorder traversal is:", res)
|
||||
print("Postorder traversal:", res)
|
||||
|
||||
@@ -19,110 +19,110 @@ class AVLTree:
|
||||
self._root = None
|
||||
|
||||
def get_root(self) -> TreeNode | None:
|
||||
"""Get binary tree root node"""
|
||||
"""Get the root of the binary tree"""
|
||||
return self._root
|
||||
|
||||
def height(self, node: TreeNode | None) -> int:
|
||||
"""Get node height"""
|
||||
# Empty node height is -1, leaf node height is 0
|
||||
"""Get the node height"""
|
||||
# An empty subtree has height -1; a leaf has height 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
|
||||
"""Update the node height"""
|
||||
# The node height equals the height of its taller 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
|
||||
"""Get the balance factor"""
|
||||
# An empty subtree has balance factor 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"""
|
||||
"""Right rotation"""
|
||||
child = node.left
|
||||
grand_child = child.right
|
||||
# Using child as pivot, rotate node to the right
|
||||
# Rotate node to the right around child
|
||||
child.right = node
|
||||
node.left = grand_child
|
||||
# Update node height
|
||||
# Update the node height
|
||||
self.update_height(node)
|
||||
self.update_height(child)
|
||||
# Return root node of subtree after rotation
|
||||
# Return the root of the rotated subtree
|
||||
return child
|
||||
|
||||
def left_rotate(self, node: TreeNode | None) -> TreeNode | None:
|
||||
"""Left rotation operation"""
|
||||
"""Left rotation"""
|
||||
child = node.right
|
||||
grand_child = child.left
|
||||
# Using child as pivot, rotate node to the left
|
||||
# Rotate node to the left around child
|
||||
child.left = node
|
||||
node.right = grand_child
|
||||
# Update node height
|
||||
# Update the node height
|
||||
self.update_height(node)
|
||||
self.update_height(child)
|
||||
# Return root node of subtree after rotation
|
||||
# Return the root of the rotated subtree
|
||||
return child
|
||||
|
||||
def rotate(self, node: TreeNode | None) -> TreeNode | None:
|
||||
"""Perform rotation operation to restore balance to this subtree"""
|
||||
# Get balance factor of node
|
||||
"""Perform rotations to restore balance in this subtree"""
|
||||
# Get the balance factor of node
|
||||
balance_factor = self.balance_factor(node)
|
||||
# Left-leaning tree
|
||||
# Left-heavy tree
|
||||
if balance_factor > 1:
|
||||
if self.balance_factor(node.left) >= 0:
|
||||
# Right rotation
|
||||
# Rotate right
|
||||
return self.right_rotate(node)
|
||||
else:
|
||||
# First left rotation then right rotation
|
||||
# Rotate left, then right
|
||||
node.left = self.left_rotate(node.left)
|
||||
return self.right_rotate(node)
|
||||
# Right-leaning tree
|
||||
# Right-heavy tree
|
||||
elif balance_factor < -1:
|
||||
if self.balance_factor(node.right) <= 0:
|
||||
# Left rotation
|
||||
# Rotate left
|
||||
return self.left_rotate(node)
|
||||
else:
|
||||
# First right rotation then left rotation
|
||||
# Rotate right, then left
|
||||
node.right = self.right_rotate(node.right)
|
||||
return self.left_rotate(node)
|
||||
# Balanced tree, no rotation needed, return directly
|
||||
# The tree is balanced; return without rotating
|
||||
return node
|
||||
|
||||
def insert(self, val):
|
||||
"""Insert node"""
|
||||
"""Insert a node"""
|
||||
self._root = self.insert_helper(self._root, val)
|
||||
|
||||
def insert_helper(self, node: TreeNode | None, val: int) -> TreeNode:
|
||||
"""Recursively insert node (helper method)"""
|
||||
"""Insert a node recursively (helper method)"""
|
||||
if node is None:
|
||||
return TreeNode(val)
|
||||
# 1. Find insertion position and insert node
|
||||
# 1. Find the insertion position and insert the 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:
|
||||
# Duplicate node not inserted, return directly
|
||||
# Return without inserting a duplicate node
|
||||
return node
|
||||
# Update node height
|
||||
# Update the node height
|
||||
self.update_height(node)
|
||||
# 2. Perform rotation operation to restore balance to this subtree
|
||||
# 2. Perform rotations to restore balance in this subtree
|
||||
return self.rotate(node)
|
||||
|
||||
def remove(self, val: int):
|
||||
"""Delete node"""
|
||||
"""Remove a node"""
|
||||
self._root = self.remove_helper(self._root, val)
|
||||
|
||||
def remove_helper(self, node: TreeNode | None, val: int) -> TreeNode | None:
|
||||
"""Recursively delete node (helper method)"""
|
||||
"""Remove a node recursively (helper method)"""
|
||||
if node is None:
|
||||
return None
|
||||
# 1. Find node and delete
|
||||
# 1. Find and remove the node
|
||||
if val < node.val:
|
||||
node.left = self.remove_helper(node.left, val)
|
||||
elif val > node.val:
|
||||
@@ -130,71 +130,71 @@ class AVLTree:
|
||||
else:
|
||||
if node.left is None or node.right is None:
|
||||
child = node.left or node.right
|
||||
# Number of child nodes = 0, delete node directly and return
|
||||
# Number of children = 0: remove node and return
|
||||
if child is None:
|
||||
return None
|
||||
# Number of child nodes = 1, delete node directly
|
||||
# Number of children = 1: remove node directly
|
||||
else:
|
||||
node = child
|
||||
else:
|
||||
# Number of child nodes = 2, delete the next node in inorder traversal and replace current node with it
|
||||
# Number of children = 2: remove the inorder successor and use its value to replace the current node value
|
||||
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
|
||||
# Update the node height
|
||||
self.update_height(node)
|
||||
# 2. Perform rotation operation to restore balance to this subtree
|
||||
# 2. Perform rotations to restore balance in this subtree
|
||||
return self.rotate(node)
|
||||
|
||||
def search(self, val: int) -> TreeNode | None:
|
||||
"""Search node"""
|
||||
"""Find a node"""
|
||||
cur = self._root
|
||||
# Loop search, exit after passing leaf node
|
||||
# Search in a loop, stopping if cur becomes None
|
||||
while cur is not None:
|
||||
# Target node is in cur's right subtree
|
||||
# If present, the target node lies in the right subtree of cur
|
||||
if cur.val < val:
|
||||
cur = cur.right
|
||||
# Target node is in cur's left subtree
|
||||
# If present, the target node lies in the left subtree of cur
|
||||
elif cur.val > val:
|
||||
cur = cur.left
|
||||
# Found target node, exit loop
|
||||
# The target node was found; exit the loop
|
||||
else:
|
||||
break
|
||||
# Return target node
|
||||
# Return the target node, or None if it was not found
|
||||
return cur
|
||||
|
||||
|
||||
"""Driver Code"""
|
||||
"""Driver code"""
|
||||
if __name__ == "__main__":
|
||||
|
||||
def test_insert(tree: AVLTree, val: int):
|
||||
tree.insert(val)
|
||||
print("\nAfter inserting node {}, AVL tree is".format(val))
|
||||
print("\nAVL tree after inserting node {}:".format(val))
|
||||
print_tree(tree.get_root())
|
||||
|
||||
def test_remove(tree: AVLTree, val: int):
|
||||
tree.remove(val)
|
||||
print("\nAfter deleting node {}, AVL tree is".format(val))
|
||||
print("\nAVL tree after removing node {}:".format(val))
|
||||
print_tree(tree.get_root())
|
||||
|
||||
# Initialize empty AVL tree
|
||||
# Initialize an empty AVL tree
|
||||
avl_tree = AVLTree()
|
||||
|
||||
# Insert nodes
|
||||
# Please pay attention to how the AVL tree maintains balance after inserting nodes
|
||||
# Insert a node
|
||||
# Observe how the AVL tree maintains balance after a node is inserted
|
||||
for val in [1, 2, 3, 4, 5, 8, 7, 9, 10, 6]:
|
||||
test_insert(avl_tree, val)
|
||||
|
||||
# Insert duplicate node
|
||||
# Insert a duplicate node
|
||||
test_insert(avl_tree, 7)
|
||||
|
||||
# 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
|
||||
# Remove a node
|
||||
# Observe how the AVL tree maintains balance after a node is removed
|
||||
test_remove(avl_tree, 8) # Remove a node with 0 children
|
||||
test_remove(avl_tree, 5) # Remove a node with 1 child
|
||||
test_remove(avl_tree, 4) # Remove a node with 2 children
|
||||
|
||||
result_node = avl_tree.search(7)
|
||||
print("\nFound node object is {}, node value = {}".format(result_node, result_node.val))
|
||||
print("\nFound node object: {}, node value = {}".format(result_node, result_node.val))
|
||||
|
||||
@@ -16,49 +16,49 @@ class BinarySearchTree:
|
||||
|
||||
def __init__(self):
|
||||
"""Constructor"""
|
||||
# Initialize empty tree
|
||||
# Initialize an empty tree
|
||||
self._root = None
|
||||
|
||||
def get_root(self) -> TreeNode | None:
|
||||
"""Get binary tree root node"""
|
||||
"""Get the root of the binary tree"""
|
||||
return self._root
|
||||
|
||||
def search(self, num: int) -> TreeNode | None:
|
||||
"""Search node"""
|
||||
"""Find a node"""
|
||||
cur = self._root
|
||||
# Loop search, exit after passing leaf node
|
||||
# Search in a loop, stopping if cur becomes None
|
||||
while cur is not None:
|
||||
# Target node is in cur's right subtree
|
||||
# If present, the target node is in the right subtree of cur
|
||||
if cur.val < num:
|
||||
cur = cur.right
|
||||
# Target node is in cur's left subtree
|
||||
# If present, the target node is in the left subtree of cur
|
||||
elif cur.val > num:
|
||||
cur = cur.left
|
||||
# Found target node, exit loop
|
||||
# The target node was found; exit the loop
|
||||
else:
|
||||
break
|
||||
return cur
|
||||
|
||||
def insert(self, num: int):
|
||||
"""Insert node"""
|
||||
# If tree is empty, initialize root node
|
||||
"""Insert a node"""
|
||||
# If the tree is empty, initialize the root node
|
||||
if self._root is None:
|
||||
self._root = TreeNode(num)
|
||||
return
|
||||
# Loop search, exit after passing leaf node
|
||||
# Search in a loop, stopping if cur becomes None
|
||||
cur, pre = self._root, None
|
||||
while cur is not None:
|
||||
# Found duplicate node, return directly
|
||||
# Return immediately if a duplicate node is found
|
||||
if cur.val == num:
|
||||
return
|
||||
pre = cur
|
||||
# Insertion position is in cur's right subtree
|
||||
# The insertion position lies in the right subtree of cur
|
||||
if cur.val < num:
|
||||
cur = cur.right
|
||||
# Insertion position is in cur's left subtree
|
||||
# The insertion position lies in the left subtree of cur
|
||||
else:
|
||||
cur = cur.left
|
||||
# Insert node
|
||||
# Insert a node
|
||||
node = TreeNode(num)
|
||||
if pre.val < num:
|
||||
pre.right = node
|
||||
@@ -66,81 +66,81 @@ class BinarySearchTree:
|
||||
pre.left = node
|
||||
|
||||
def remove(self, num: int):
|
||||
"""Delete node"""
|
||||
# If tree is empty, return directly
|
||||
"""Remove a node"""
|
||||
# Return immediately if the tree is empty
|
||||
if self._root is None:
|
||||
return
|
||||
# Loop search, exit after passing leaf node
|
||||
# Search in a loop, stopping if cur becomes None
|
||||
cur, pre = self._root, None
|
||||
while cur is not None:
|
||||
# Found node to delete, exit loop
|
||||
# The node to remove was found; exit the loop
|
||||
if cur.val == num:
|
||||
break
|
||||
pre = cur
|
||||
# Node to delete is in cur's right subtree
|
||||
# If present, the node to remove is in the right subtree of cur
|
||||
if cur.val < num:
|
||||
cur = cur.right
|
||||
# Node to delete is in cur's left subtree
|
||||
# If present, the node to remove is in the left subtree of cur
|
||||
else:
|
||||
cur = cur.left
|
||||
# If no node to delete, return directly
|
||||
# Return immediately if the node to remove does not exist
|
||||
if cur is None:
|
||||
return
|
||||
|
||||
# Number of child nodes = 0 or 1
|
||||
# Number of children = 0 or 1
|
||||
if cur.left is None or cur.right is None:
|
||||
# When number of child nodes = 0 / 1, child = null / that child node
|
||||
# With 0 or 1 child, child is None or that child, respectively
|
||||
child = cur.left or cur.right
|
||||
# Delete node cur
|
||||
# Remove node cur
|
||||
if cur != self._root:
|
||||
if pre.left == cur:
|
||||
pre.left = child
|
||||
else:
|
||||
pre.right = child
|
||||
else:
|
||||
# If deleted node is root node, reassign root node
|
||||
# If the removed node is the root, assign the new root
|
||||
self._root = child
|
||||
# Number of child nodes = 2
|
||||
# Number of children = 2
|
||||
else:
|
||||
# Get next node of cur in inorder traversal
|
||||
# Get the inorder successor of cur
|
||||
tmp: TreeNode = cur.right
|
||||
while tmp.left is not None:
|
||||
tmp = tmp.left
|
||||
# Recursively delete node tmp
|
||||
# Recursively remove node tmp
|
||||
self.remove(tmp.val)
|
||||
# Replace cur with tmp
|
||||
# Replace the value of cur with the value of tmp
|
||||
cur.val = tmp.val
|
||||
|
||||
|
||||
"""Driver Code"""
|
||||
"""Driver code"""
|
||||
if __name__ == "__main__":
|
||||
# Initialize binary search tree
|
||||
# Initialize the binary search tree
|
||||
bst = BinarySearchTree()
|
||||
nums = [8, 4, 12, 2, 6, 10, 14, 1, 3, 5, 7, 9, 11, 13, 15]
|
||||
# Please note that different insertion orders will generate different binary trees, this sequence can generate a perfect binary tree
|
||||
# Different insertion orders produce different binary trees; this sequence produces a perfect binary tree
|
||||
for num in nums:
|
||||
bst.insert(num)
|
||||
print("\nInitialized binary tree is\n")
|
||||
print("\nThe initialized binary tree is:\n")
|
||||
print_tree(bst.get_root())
|
||||
|
||||
# Search node
|
||||
# Find a node
|
||||
node = bst.search(7)
|
||||
print("\nFound node object is: {}, node value = {}".format(node, node.val))
|
||||
print("\nFound node object: {}, node value = {}".format(node, node.val))
|
||||
|
||||
# Insert node
|
||||
# Insert a node
|
||||
bst.insert(16)
|
||||
print("\nAfter inserting node 16, binary tree is\n")
|
||||
print("\nBinary tree after inserting node 16:\n")
|
||||
print_tree(bst.get_root())
|
||||
|
||||
# Delete node
|
||||
# Remove a node
|
||||
bst.remove(1)
|
||||
print("\nAfter deleting node 1, binary tree is\n")
|
||||
print("\nBinary tree after removing node 1:\n")
|
||||
print_tree(bst.get_root())
|
||||
|
||||
bst.remove(2)
|
||||
print("\nAfter deleting node 2, binary tree is\n")
|
||||
print("\nBinary tree after removing node 2:\n")
|
||||
print_tree(bst.get_root())
|
||||
|
||||
bst.remove(4)
|
||||
print("\nAfter deleting node 4, binary tree is\n")
|
||||
print("\nBinary tree after removing node 4:\n")
|
||||
print_tree(bst.get_root())
|
||||
|
||||
@@ -11,31 +11,31 @@ sys.path.append(str(Path(__file__).parent.parent))
|
||||
from modules import TreeNode, print_tree
|
||||
|
||||
|
||||
"""Driver Code"""
|
||||
"""Driver code"""
|
||||
if __name__ == "__main__":
|
||||
# Initialize binary tree
|
||||
# Initialize nodes
|
||||
# Initialize the binary tree
|
||||
# Initialize the nodes
|
||||
n1 = TreeNode(val=1)
|
||||
n2 = TreeNode(val=2)
|
||||
n3 = TreeNode(val=3)
|
||||
n4 = TreeNode(val=4)
|
||||
n5 = TreeNode(val=5)
|
||||
# Build references (pointers) between nodes
|
||||
# Set up references (pointers) between the nodes
|
||||
n1.left = n2
|
||||
n1.right = n3
|
||||
n2.left = n4
|
||||
n2.right = n5
|
||||
print("\nInitialize binary tree\n")
|
||||
print("\nInitialize the binary tree\n")
|
||||
print_tree(n1)
|
||||
|
||||
# Insert and delete nodes
|
||||
# Insert and remove nodes
|
||||
P = TreeNode(0)
|
||||
# Insert node P between n1 -> n2
|
||||
# Insert node P between n1 and n2 in n1 -> n2
|
||||
n1.left = P
|
||||
P.left = n2
|
||||
print("\nAfter inserting node P\n")
|
||||
print("\nAfter inserting node P:\n")
|
||||
print_tree(n1)
|
||||
# Delete node
|
||||
# Remove a node
|
||||
n1.left = n2
|
||||
print("\nAfter deleting node P\n")
|
||||
print("\nAfter removing node P:\n")
|
||||
print_tree(n1)
|
||||
|
||||
@@ -14,29 +14,29 @@ from collections import deque
|
||||
|
||||
def level_order(root: TreeNode | None) -> list[int]:
|
||||
"""Level-order traversal"""
|
||||
# Initialize queue, add root node
|
||||
# Initialize a queue and enqueue the root
|
||||
queue: deque[TreeNode] = deque()
|
||||
queue.append(root)
|
||||
# Initialize a list to save the traversal sequence
|
||||
# Initialize a list to store the traversal sequence
|
||||
res = []
|
||||
while queue:
|
||||
node: TreeNode = queue.popleft() # Dequeue
|
||||
res.append(node.val) # Save node value
|
||||
node: TreeNode = queue.popleft() # Dequeue from the queue
|
||||
res.append(node.val) # Store the node value
|
||||
if node.left is not None:
|
||||
queue.append(node.left) # Left child node enqueue
|
||||
queue.append(node.left) # Enqueue the left child
|
||||
if node.right is not None:
|
||||
queue.append(node.right) # Right child node enqueue
|
||||
queue.append(node.right) # Enqueue the right child
|
||||
return res
|
||||
|
||||
|
||||
"""Driver Code"""
|
||||
"""Driver code"""
|
||||
if __name__ == "__main__":
|
||||
# Initialize binary tree
|
||||
# Here we use a function to generate a binary tree directly from an array
|
||||
# Initialize the binary tree
|
||||
# Use a helper function that builds 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("\nInitialize the binary tree\n")
|
||||
print_tree(root)
|
||||
|
||||
# Level-order traversal
|
||||
res: list[int] = level_order(root)
|
||||
print("\nLevel-order traversal node print sequence = ", res)
|
||||
print("\nNode sequence from level-order traversal = ", res)
|
||||
|
||||
@@ -15,7 +15,7 @@ def pre_order(root: TreeNode | None):
|
||||
"""Preorder traversal"""
|
||||
if root is None:
|
||||
return
|
||||
# Visit priority: root node -> left subtree -> right subtree
|
||||
# Visit order: root -> left subtree -> right subtree
|
||||
res.append(root.val)
|
||||
pre_order(root=root.left)
|
||||
pre_order(root=root.right)
|
||||
@@ -25,7 +25,7 @@ def in_order(root: TreeNode | None):
|
||||
"""Inorder traversal"""
|
||||
if root is None:
|
||||
return
|
||||
# Visit priority: left subtree -> root node -> right subtree
|
||||
# Visit order: left subtree -> root -> right subtree
|
||||
in_order(root=root.left)
|
||||
res.append(root.val)
|
||||
in_order(root=root.right)
|
||||
@@ -35,31 +35,31 @@ def post_order(root: TreeNode | None):
|
||||
"""Postorder traversal"""
|
||||
if root is None:
|
||||
return
|
||||
# Visit priority: left subtree -> right subtree -> root node
|
||||
# Visit order: left subtree -> right subtree -> root
|
||||
post_order(root=root.left)
|
||||
post_order(root=root.right)
|
||||
res.append(root.val)
|
||||
|
||||
|
||||
"""Driver Code"""
|
||||
"""Driver code"""
|
||||
if __name__ == "__main__":
|
||||
# Initialize binary tree
|
||||
# Here we use a function to generate a binary tree directly from an array
|
||||
# Initialize the binary tree
|
||||
# Use a helper function that builds 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("\nInitialize the binary tree\n")
|
||||
print_tree(root)
|
||||
|
||||
# Preorder traversal
|
||||
res = []
|
||||
pre_order(root)
|
||||
print("\nPreorder traversal node print sequence = ", res)
|
||||
print("\nNode sequence from preorder traversal = ", res)
|
||||
|
||||
# Inorder traversal
|
||||
res.clear()
|
||||
in_order(root)
|
||||
print("\nInorder traversal node print sequence = ", res)
|
||||
print("\nNode sequence from inorder traversal = ", res)
|
||||
|
||||
# Postorder traversal
|
||||
res.clear()
|
||||
post_order(root)
|
||||
print("\nPostorder traversal node print sequence = ", res)
|
||||
print("\nNode sequence from postorder traversal = ", res)
|
||||
|
||||
Reference in New Issue
Block a user