我已经看到很多DFS的实现使用名为visited的布尔变量,我不想在我的代码中使用它。在考虑一个场景,我们有一个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;
}
答案 0 :(得分:0)
确实告诉迭代树行走它需要一个&#34; up&#34;节点上的链接(或保存它们)以便能够回溯。你做到这一点 - 只保存不#34; up&#34;链接,但直接下一个链接后回溯。另一方面,步骤之间没有相互依赖关系。有关如何区分迭代和伪装的递归,请参阅Is this function recursive even though it doesn't call itself?。
另请参阅Iterative tree walking以了解算法的概述。
现在,计算复杂性。原则可以在Big O, how do you calculate/approximate it?找到。
你这样做:
所以,确实,它是 O(N)。