mirror of
https://github.com/krahets/hello-algo.git
synced 2025-07-10 08:50:20 +08:00
Bug fixes and improvements (#1298)
* Fix is_empty() implementation in the stack and queue chapter * Update en/CONTRIBUTING.md * Remove "剩余" from the state definition of knapsack problem * Sync zh and zh-hant versions * Update the stylesheets of code tabs * Fix quick_sort.rb * Fix TS code * Update chapter_paperbook * Upload the manuscript of 0.1 section * Fix binary_tree_dfs.rb * Bug fixes * Update README * Update README * Update README * Update README.md * Update README * Sync zh and zh-hant versions * Bug fixes
This commit is contained in:
@ -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
|
||||
|
Reference in New Issue
Block a user