I have written this code for DFS in a binary tree and would like improvements on it.
// Method 1: Recursive DFS
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);
}
}
//=============================================================================
// Method 2: DFS using stack
public static boolean DFS2(Node root, int k){
if(root == null){
return false;
}
Stack<Node> stack = new Stack<Node>();
stack.push(root);
while(!stack.isEmpty()){
Node current = stack.pop();
if(current.data == k){
return true; //Found the value!
}
if(current.right != null){
stack.push(current.right);
}
if(current.left != null){ // As we want to visit left
stack.push(current.left); //child first, we must push this node last
}
}
return false; // Not found
}
//============================================================================
// Method 3: DFS by marking visited nodes - using stack
public static boolean DFS4(Node root, int k) {
if(root == null){
return false;
}
Stack<Node> stack = new Stack<Node>();
stack.push(root);
while (!stack.isEmpty()) {
Node current = stack.pop();
if(current.data == k){
return true;
}
current.visited = true;
if (current.right != null && current.right.visited == false) {
stack.push(current.right);
}
if (current.left != null && current.left.visited == false) {
stack.push(current.left);
}
}
return false;
}
//============================================================================
// Method 4: DFS (search) by putting visited nodes in a hash set - using stack
public static boolean DFS5(Node root, int k) {
if(root == null){
return false;
}
Stack<Node> stack = new Stack<Node>();
HashSet<Node> hs = new HashSet<Node>();
stack.push(root);
while (!stack.isEmpty()) {
Node current = stack.pop();
hs.add(current);
if(current.data == k){
return true;
}
if (current.right != null && !hs.contains(current.right)) {
stack.push(current.right);
}
if (current.left != null && !hs.contains(current.left)) {
stack.push(current.left);
}
}
return false;
}