预订遍历是深度优先方法吗?

时间:2016-09-14 18:00:05

标签: algorithm recursion binary-search-tree depth-first-search

预订序是否是深度优先算法?我在下面的搜索中使用它。我已经包含了下面的代码。

public bool DFS1(int value, BSTNode root)
{    // Pre-order search

    if (root == null)
        return false;

    if (root.data == value)
    {
        Console.WriteLine("found");
        return true;
    }

    DFS1(value, root.left); //vist the left node
    return DFS1(value, root.right); // vist the right node.
}

1 个答案:

答案 0 :(得分:3)

是的,它是深度优先的:在您查看原始根的右侧节点之前,您将完全完成左侧子树。但是,您需要考虑左搜索的结果。目前,如果最右边的节点具有目标值,则返回 true

return DFS1(value, root.left) or
       DFS1(value, root.right)

大多数编译器会对此进行优化(短路),因此如果左侧返回 true ,则右侧将不会执行。如果没有,你可以自己写:

if (DFS1(value, root.left))
    return true;
else
    return DFS1(value, root.right);