feat: add ruby codes - chapter tree (#1288)

This commit is contained in:
khoaxuantu
2024-04-19 14:50:43 +07:00
committed by GitHub
parent a587b01c4d
commit 19488b13c4
7 changed files with 672 additions and 0 deletions
+35
View File
@@ -16,3 +16,38 @@ class TreeNode
@height = 0
end
end
### 将列表反序列化为二叉数树:递归 ###
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