的葉子下面的問題工作:查找二叉樹
Given a binary tree, collect a tree's nodes as if you were doing this: Collect and remove all leaves, repeat until the tree is empty.
Example:
Given binary tree
1
/\
2 3
/\
4 5
Returns [4, 5, 3], [2], [1].
Explanation:
1. Removing the leaves [4, 5, 3] would result in this tree:
1
/
2
2. Now removing the leaf [2] would result in this tree:
1
3. Now removing the leaf [1] would result in the empty tree:
[]
Returns [4, 5, 3], [2], [1].
我的想法是如下所示的簡單遞歸算法。這個想法是找到左側子樹和右側子樹的葉子,並將它們編織成深度在右側子樹中。我已經非常徹底地測試了'編織'方法,我認爲它很好。我關心的是我的遞歸實現 - 我正在從正確的答案中獲得答案,並且不知道爲什麼。
下面是我的代碼示例輸入/輸出:
def find_leaves(root)
return [] if root.nil?
#create leaf_arr of root.left and root.right
#weave them in order.
#add the root
left_arr = find_leaves(root.left)
right_arr = find_leaves(root.right)
weave(left_arr, right_arr) << [root]
end
def weave(arr1, arr2) #these are 2d arrs
i = 0
until i == arr1.length || i == arr2.length #potential nil/empty case here
arr1[i] += arr2[i]
i += 1
end
if i < arr2.length
#either arr 1 or arr2 isn't finished. if arr1 isn't finished, we're done. if arr2 isnt finished, do the below:
until i == arr2.length
arr1 << arr2[i]
i += 1
end
end
arr1
end
樣品輸入/輸出/正確答案:
Run Code Result: ×
input: [1,2,3,4,5]
Your answer: [[[4],[5],[3]],[[2,4,5]],[[1,2,3,4,5]]]
Expected answer: [[4,5,3],[2],[1]]
我打印的left_arr和right_arr變量,它們的輸出看起來很好,我已經對我的編織算法進行了壓力測試。我在概念上在這裏嗎?
我提供了兩個工作示例,我希望這有助於!你開始爬上谷歌搜索結果,所以如果其中一個答案是正確的,請標記一個正確的答案。這將有助於未來的人們提出相同的問題! – OneNeptune