【问题标题】:Implementation of DFS using iterative approach in java在java中使用迭代方法实现DFS
【发布时间】:2016-01-09 05:33:39
【问题描述】:

我见过很多使用名为visited 的布尔变量的DFS 实现,我不想在我的代码中使用它。在考虑一个场景时,我们有一个 Node 类,该类包含对与其子节点相对应的左右节点的引用以及可以是任何 Object 的数据,这种方法可以适用于二叉树来计算 dfs 吗?我有一个场景,我没有邻接列表或矩阵。

以下代码是 DFS 的良好实现吗?代码的时间复杂度是 O(n) 吗?

public void dfsForTree(BSTNode root) {
    Stack<BSTNode> s = new Stack<BSTNode>();
    BSTNode node;
    if (root == null) {
        return;
    }
    s.push(root);
    while (!s.isEmpty()) {
        node = s.pop();
        System.out.println(node.getData());
        if (node != null) {

            if (node.getRight() != null) {
                s.push(node.getRight);
            }
            if (node.getLeft != null) {
                s.push(node.getLeft);
            }

        }
    }
}

BSTNode 类实现:

public class BSTNode {

private BSTNode left;
private BSTNode right;
private int data;

/* Constructor */
public BSTNode(int n) {
    left = null;
    right = null;
    data = n;
}
/* Function to set left node */

public void setLeft(BSTNode n) {
    left = n;
}
/* Function to set right node */

public void setRight(BSTNode n) {
    right = n;
}
/* Function to get left node */

public BSTNode getLeft() {
    return left;
}
/* Function to get right node */

public BSTNode getRight() {
    return right;
}
/* Function to set data to node */

public void setData(int d) {
    data = d;
}
/* Function to get data from node */

public int getData() {
    return data;
}

【问题讨论】:

标签: java iteration binary-tree depth-first-search


【解决方案1】:

迭代树遍历的一个明确说法是它需要节点上的“向上”链接(或保存它们)才能回溯。你这样做 - 只保存不“向上”链接,而是直接保存下一个链接以在回溯后进行。另一方面,步骤之间没有相互依赖关系。请参阅Is this function recursive even though it doesn't call itself? 了解如何区分迭代和伪装递归。

有关算法的概述,另请参阅 Iterative tree walking

现在,对于计算复杂性。原理见Big O, how do you calculate/approximate it?

你这样做:

  • 处理每个节点
    • 恰好一次
  • 从堆栈中推送和弹出节点
    • 每个节点也只被推送和弹出一次

所以,确实是O(N)

【讨论】:

    猜你喜欢
    • 2018-04-05
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-02-27
    • 2015-01-17
    • 2016-04-16
    相关资源
    最近更新 更多