【发布时间】: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