-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathDepthFirstDFS.java
More file actions
33 lines (25 loc) · 817 Bytes
/
DepthFirstDFS.java
File metadata and controls
33 lines (25 loc) · 817 Bytes
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
package Trees;
import java.util.Stack;
public class DepthFirstDFS {
/* Depth First Search algorithm, it is the same as inorder. */
public static void dfs(Node root) {
Stack<Node> st = new Stack<>();
if (root != null)
st.push(root);
while (st.size() > 0) {
Node temp = st.peek();
/* If there is a left part add it to the stack and de-attach it. */
if (temp.left != null) {
st.push(temp.left);
temp.left = null; /* Very Important Step */
} else {
st.pop();
System.out.print(temp.val + " ");
if (temp.right != null)
st.push(temp.right);
}
}
}
public static void main(String[] args) {
}
}