Files
hello-algo/ja/codes/ruby/utils/tree_node.rb
T
Yudong JinandClaude Opus 5.5 b113cb425a Cite the shared TreeNode for the AVL node and the C binary tree node (#2037)
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]>
2026-11-16 05:51:36 +08:00

56 lines
1.5 KiB
Ruby

=begin
File: tree_node.rb
Created Time: 2024-03-30
Author: Xuan Khoa Tu Nguyen ([email protected])
=end
# [region]{tree_node}
### 二分木のノードクラス ###
class TreeNode
attr_accessor :val # ノードの値
attr_accessor :height # ノードの高さ
attr_accessor :left # 左の子ノードへの参照
attr_accessor :right # 右の子ノードへの参照
def initialize(val=0)
@val = val
@height = 0
end
end
# [endregion]{tree_node}
### リストをデシリアライズして二分木にする:再帰 ###
def arr_to_tree_dfs(arr, i)
# インデックスが配列の長さを超えるか、対応する要素が nil の場合、nil を返す
return if i < 0 || i >= arr.length || arr[i].nil?
# 現在のノードを構築する
root = TreeNode.new(arr[i])
# 左右の部分木を再帰的に構築する
root.left = arr_to_tree_dfs(arr, 2 * i + 1)
root.right = arr_to_tree_dfs(arr, 2 * i + 2)
root
end
### リストから二分木へデシリアライズ ###
def arr_to_tree(arr)
arr_to_tree_dfs(arr, 0)
end
### 二分木をシリアライズしてリストにする:再帰 ###
def tree_to_arr_dfs(root, i, res)
return if root.nil?
res += Array.new(i - res.length + 1) if i >= res.length
res[i] = root.val
tree_to_arr_dfs(root.left, 2 * i + 1, res)
tree_to_arr_dfs(root.right, 2 * i + 2, res)
end
### 二分木をシリアライズしてリストにする ###
def tree_to_arr(root)
res = []
tree_to_arr_dfs(root, 0, res)
res
end