Ruby recursive DFS method

早过忘川 提交于 2019-12-22 09:57:17

问题


I have some troubles with recursive method for depth first search algorithm implementation. Here's the binary tree photo:

The method works well with the right side of the tree (55, 89, 144), but it returns nil when it comes to the left side, even though it puts "yes". So, what's wrong with the code? The node is an instance of Node class that has value (integer) and links to the left and right child (other instances of Node class) which is nil if it doesn't have the child from that side.

Here's the method code:

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

回答1:


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.



来源:https://stackoverflow.com/questions/31192489/ruby-recursive-dfs-method

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