Ruby recursive DFS method

a 夏天 提交于 2019-12-05 20:59:40

Because depth_first_search(node.child_left, target) isn't the last line of your method, its value will never be returned. You need to return its value if its value is not nil. Here is an example of one way to solve your problem:

def depth_first_search(node, target)
    if node.value == target
        puts "yes"
        return node
    end
    left = depth_first_search(node.child_left, target) if node.child_left
    right = depth_first_search(node.child_right, target) if node.child_right
    left or right
end

Note that this example will search the right subtree even if the correct node is found on the left subtree, which is inefficient.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!