mirror of
https://github.com/krahets/hello-algo.git
synced 2026-11-29 18:32:09 +08:00
Batch 3b of the runnable-snippets plan. avl_tree_node now cites each language's shared TreeNode in all 13 languages, and the C tree_node_class shares the same region. Rust gets an import region; Java, C#, Swift and Kotlin skip their serialization helpers with an adjacent region. The shared nodes gain reviewed field comments in C++ and Rust, aligned comments in Java, Swift and Kotlin, and a spacing fix in JavaScript. The AVL section adds one sentence saying the shared node class already has height. Four ru Rust files whose multi-line statements had collapsed into literal \n now compile again. en, ja, ko and zh-hant are regenerated; ru is synced by hand. Co-Authored-By: Claude Opus 5.5 <[email protected]>
72 lines
2.2 KiB
Python
72 lines
2.2 KiB
Python
"""
|
|
File: tree_node.py
|
|
Created Time: 2021-12-11
|
|
Author: krahets ([email protected])
|
|
"""
|
|
|
|
from collections import deque
|
|
|
|
|
|
# [region]{tree_node}
|
|
class TreeNode:
|
|
"""Binary tree node class"""
|
|
|
|
def __init__(self, val: int = 0):
|
|
self.val: int = val # Node value
|
|
self.height: int = 0 # Node height
|
|
self.left: TreeNode | None = None # Reference to the left child
|
|
self.right: TreeNode | None = None # Reference to the right child
|
|
# [endregion]{tree_node}
|
|
|
|
# For the serialization rules, see:
|
|
# https://www.hello-algo.com/en/chapter_tree/array_representation_of_tree/
|
|
# Array representation of the binary tree:
|
|
# [1, 2, 3, 4, None, 6, 7, 8, 9, None, None, 12, None, None, 15]
|
|
# Linked representation of the binary tree:
|
|
# /——— 15
|
|
# /——— 7
|
|
# /——— 3
|
|
# | \——— 6
|
|
# | \——— 12
|
|
# ——— 1
|
|
# \——— 2
|
|
# | /——— 9
|
|
# \——— 4
|
|
# \——— 8
|
|
|
|
|
|
def list_to_tree_dfs(arr: list[int], i: int) -> TreeNode | None:
|
|
"""Deserialize a list into a binary tree: recursion"""
|
|
# Return None if the index is out of bounds or the corresponding element is None
|
|
if i < 0 or i >= len(arr) or arr[i] is None:
|
|
return None
|
|
# Create the current node
|
|
root = TreeNode(arr[i])
|
|
# Recursively build the left and right subtrees
|
|
root.left = list_to_tree_dfs(arr, 2 * i + 1)
|
|
root.right = list_to_tree_dfs(arr, 2 * i + 2)
|
|
return root
|
|
|
|
|
|
def list_to_tree(arr: list[int]) -> TreeNode | None:
|
|
"""Deserialize a list into a binary tree"""
|
|
return list_to_tree_dfs(arr, 0)
|
|
|
|
|
|
def tree_to_list_dfs(root: TreeNode, i: int, res: list[int]) -> list[int]:
|
|
"""Serialize a binary tree into a list: recursion"""
|
|
if root is None:
|
|
return
|
|
if i >= len(res):
|
|
res += [None] * (i - len(res) + 1)
|
|
res[i] = root.val
|
|
tree_to_list_dfs(root.left, 2 * i + 1, res)
|
|
tree_to_list_dfs(root.right, 2 * i + 2, res)
|
|
|
|
|
|
def tree_to_list(root: TreeNode | None) -> list[int]:
|
|
"""Serialize a binary tree into a list"""
|
|
res = []
|
|
tree_to_list_dfs(root, 0, res)
|
|
return res
|