##General
Your methods all use a C-like system for the tree Nodes. In Java, the tree should be an Object, and the Node class should not be publicly visible. In other words, you should have something like:
public class BinaryTree {
private static class Node {
private Node left, right;
private int value;
.....
}
private Node root = null;
public searchDFS1(int value) {
.....
}
public searchDFS2(int value) {
.....
}
public searchDFS3(int value) {
.....
}
Note how the methods are no longer static, and their implementation can have private access to the root instance (if any).
##DFS1
public static boolean DFS(Node root, int k){
if(root == null){
return false;
} else if (root.data == k){
return true;
} else {
return DFS(root.left, k) || DFS(root.right, k);
}
}
This is a typical implementation of a recursive DFS. I see no issues with the implementation other than the static implementation. Typically, you would do it like:
public boolean DFS(int k) {
return recurse(root, k);
}
private boolean recurseDFS(Node node, int k) {
if(node == null) {
return false;
}
return node.data == k || recurseDFS(node.left, k) || recurseDFS(node.right, k);
}
I would not worry too much about the stack overflow. Java typically has 10's of thousands of levels it will manage before overflow. On a reasonably balanced tree this would be more than enough.
##DFS2
Again with the static, but the rest of the implementation looks fine. The Stack based system is a head-scratcher, but it works well. It allows for the stack to simulate a recursive approach, and that's what we would expect.
Your use of isEmpty()
is good, and often I see people using size() != 0
, so nice there.
##DFS3
You messed up your naming, why is //DFS3
got the method name DFS4
? Consistency please.
THis one using a visited marker on the node is a real problem. The code is no longer reentrant, and you have to reset each node before you can call the function again.
##DFS4 (or 5, depending).
Using a HashSet is an OK option, but it requires a lot more space to manage. Additionally, it depends on the hashcode and equals methods, so would be slower.
I would avoid it.