的叶子下面的问题工作:查找二叉树
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